# Learning to Code — Part 7a: Arrays & Strings

I just finished Part 6 about 5 or 10 minutes ago, but I’ve got some momentum now and decided to just move right along to the next section within the SoloLearn app, called Arrays & Strings.

# ARRAYS

An array is a data structure that is used to store a collection of data. You can think of it as a collection of variables of the same type.

A simple example of when and why you’d create an array would be, if you need to store 100 numbers, you don’t need to create 100 variables, and assign a number to each one. Instead, you can create a single array that stores 100 numbers. The following is an example of the declaration of an array:

`int[] myArray;`

This declares an array that contains integers. The square brackets ([ ]) are used to specify the number of elements that the array should hold. Similar to instantiating an object of a particular class type, we also have to use the new keyword to instantiate an array (because it too is an object), like this:

`int[ ] myArray = new int;`

This code instantiates an new array called myArray, which holds 5 integers. Once the array object is created, you can assign values to the individual elements within the array using the index number. Basically what this means is that each “spot” within an array that holds an element has a separate number. Arrays are zero-indexed, meaning the first spot is at index 0. The second spot is at index 1. The third spot is at index 2, and so on.

`int[] myArray = new int;myArray = 23;`

In the code above, a new array object is instantiated, and is set to be able to hold 5 integers. The value 23 is stored in the first spot (known as index 0).

There are a number of efficiencies that we can employ when creating arrays. First, we can provide initial values when creating the array, like this:

`string[] name = new string {“John”, “Mary”, “Jessica”};`

This code creates a new array object called name, configures it to hold 3 integers, assigns the first spot (or index 0) the string “John”, the second spot (or index 1) the string “Mary”, and the third sport (or index 2) the string “Jessica”.

Array are even smart enough to count the number of objects being provided for the array and, as a result, we don’t have to specify the amount beforehand. Like this:

`string[] name = {John”, “May”, “Jessica”};`

This code is the same as the previous code, except that we didn’t enter the number 3 to indicate the number of spots. The number of values provided for the array caused it to “know” that it needed 3 spots automatically.

Finally, the third efficiency is that we really don’t need the new operator so, as a result, it can be written like this:

`string[] name = {“John”, “Mary”, “Jessica”};`

Again, this code is the same as above, but the C# compiler is smart enough to “know” that I’m creating a new array called names, which holds 3 elements of the string data type, and what those elements are.

You can also access the values of specific elements within the array by using its index number, like this:

`Console.WriteLine(name); This code would return the value Jessica.Console.WriteLine(name); This code would return the value John.`

Sometimes you’ll need to look through each element within an array, and make assignments based on a calculation. This can be accomplished with loops, as in the following code:

`int[ ] a = new int;for (int k = 0; k < 10; k++) {     a[k] = k*2;}`

When executed, this code will create a new array, called a, that can hold 10 integers. When the for loop is reached, the following happens:

• A variable is created called k, with a data type of integer, and an initial value of 0.
• The condition of whether the current value of k is less than 10 is checked. In other words, is 0 less that 10?
• Since it is, the next line of code is executed which says, within the array called a, in position k (or position 0) assign a value of k*2 (or 0*2) which equals 0. In other words, within the array called a, at position 0, assign the value 0.
• Finally, the value of k is incremented from 0 to 1.
• The condition of the loop, k < 10 is checked once again. In other words, is 1 less than 10?
• Since it is, the next line of code is executed which says, within the array called a, in position k (or position 1) assign a value of k*2 (or 1*2) which equals 2. In other words, within the array called a, at position 1, assign the value 2.
• The value of k is incremented from 1 to 2.
• The condition of the loop, k < 10 is checked once again. In other words, is 2 less than 10?
• Since it is, the next line of code is executed which says, within the array called a, in position k (or position 2) assign a value of k*2 (or 2*2) which equals 4. In other words, within the array called a, at position 2, assign the value 4.

The for loop will continue adding values to each position within the array until the condition of the loop, k < 10, is no longer true (which would be when k is equal to 10). As a result, the array is being populated with values in each indexed position as follows:

You can use the same technique to read the values of an array. For example, to read the values within each spot in the array we just created, the code would look like this:

`for (int k = 0; k < 10; k++) {     Console.WriteLine(a[k]);}`

When the code above is executed, the following happens:

• A variable is created called k, with a data type of integer, and an initial value of 0.
• The condition of whether the current value of k is less than 10 is checked. In other words, is 0 less that 10?
• Since it is, the next line of code is executed which says, within the array called a, in position k (or position 0) print the value, which, at this point, is 0 (as seen in the table above).

The for loop will continue printing the values at each position within the array until the condition of the loop, k < 10, is no longer true (which would be when k is equal to 10).

While this process will work as described, it is more efficient to use the foreach loop (versus the for loop). So, instead of using the for loop in the previous example for retrieving each element in the array, we could use the following:

`foreach (int k in a) {     Console.WriteLine(k);}`

According to the SoloLearn app:

The foreach loop iterates through the array a and assigns the value of the current element to the variable k at each iteration of the loop.

I like to think of it this way, however:

For each value within the array called a, one at a time, assign it to a new variable called k, whose data type is integer, and print it to the screen.

This loop will continue until after it reaches the final element in the array. One thing that the app mentions to keep in mind is that the variable created along with the foreach loop should have the same data type as the array itself. That said, you can also use the following efficiency so you don’t have to know what that data type is:

`foreach (var k in a) {     Console.WriteLine(k);}`

The var keyword will cause the compiler to determine the appropriate data type for itself. In addition to setting and retrieving the values within an array, you can perform calculations on one or more of them. For example, to calculate the sum of all elements in array, the code would look like this:

`int{ } are = {11,35,62,555,989};int sum = 0;foreach (int x in arr) {     sum += x;}Console.WriteLine(sum);`

When executed, this code will do the following:

• An array called arr is created with the values 11, 35, 62, 555 and 989 as it’s values. Note that the fact that they’re integers and that there are 5 of them will be automatically determined.
• Next, for each value with the array called arr, one at a time, assign it to a new variable called x, whose data type is integer.
• Set the variable sum to be equal to the value of sum plus x, or sum = sum + x. At first, the variable sum has no value, so initially, this line of code is the equivalent of sum = 0 + 11, or sum = 11.
• The next time through, when we do sum = sum + x, it’s the equivalent of saying sum = 11 + 35, or sum = 46.
• The next time through, when we do sum = sum + x, it’s the equivalent of saying sum = 46 + 62, or sum = 108.

Each time through, the code will add the previously calculated value (i.e. the sum of all elements up to, but not including, the current one) and add it to the next value within the array. Eventually, all values will be added together, and the total, which is 1652, will be printed to the screen.

# MULTIDIMENSIONAL ARRAYS

The name of the next section, Multidimensional Arrays, makes my head spin. But, here goes…

The app states that an array can have multiple dimensions, and is declared like this:

`int[ , ] x = new int[3,4];`

In plain English, a new two dimensional array called x is created where there are 3 elements in one direction, and 4 elements in the other. The SoloLearn app has the following table to help visualize this better:

Before going to the next section, my interpretation of the entries within the cells describe the “indexed coordinates” of that element, similar to how each element in the first kind of array we learned about (presumably, a single dimensional array) had “indexed positions”. So…

• x [ 0 ] [ 0 ] means position 0,0 within the array called x (or the cell 1 column in from the left, and 1 row down from the top).
• x [ 1 ] [ 1 ] means position 1,1 within the array called x (or the cell 2 columns in from the left, and 2 rows down from the top).
• x [ 2 ] [ 3 ] means position 2,3 within the array called x (or the cell 4 columns in from the left, and 3 rows down from the top).

Initializing multidimensional arrays is done in the same way we previously initialized a single dimensional array:

`int[ , ] someNums = { {2, 3}, {5, 6}, {4, 6} };`

This code creates an array called someNums that has three rows and two columns, and I think I can see how that can be easily determined:

• On the left side of the equal sign, between the brackets there’s a single space on either side of the single comma, meaning 2 spaces or 2 columns.
• On the right side of the equal sign, there are three sets of numbers within the curly brackets, meaning 3 rows.
• The number of values within each of those curly brackets is the same as the number of spaces within the brackets on the left side of the equal sign, which is 2.

I know that seems like an over-complication, but it hammers home the concept for me. To use the same table concept above, it would initially look like this:

SomeNums[2, 0] is the equivalent of saying give me the value at the intersection of the third row of the first column.

It’s worth noting that originally, the description I just wrote was written on the SoloLearn app, like this:

For example someNums[2, 0] will return the value 4, as it accessed the first column of the third row.

To me, by saying “first column” first, but having the fact that the zero in the code, which is second, be what is being referred to is confusing. The “2” means index position 2 or the third row, and the “0” means index position 0 or the first column. In other words:

Now, however, when I look again at the line of code, I can’t quite figure out where each of the numbers would fit in the table.

Here’s the line of code:

`int[ , ] someNumbs = { {2, 3}, {5, 6}, {4, 6} };`

On the SoloLearn page below that, when you click the Try It Yourself button, and then click the RUN button, it creates a table of the values in their assigned position. Here’s the code:

`for (int k = 0; k < 3; k++) {     for (int j = 0; j < 2; j++) {          Console.Write(someNums[k, j] + “ “);     }     Console.WriteLine()}`

Before walking through how this code works, here’s what it looks like when you run the code:

`2 35 64 6`

So here are my conclusions based on this result:

• Within int[ , ] someNums = { {2, 3}, {5, 6}, {4, 6} }; there are 3 sets of bracketed values. The table, as a result of running the code, has 3 rows. So, the number of sets of bracketted values is equal to the number of ROWS in the table.
• Within int[ , ] someNums = { {2, 3}, {5, 6}, {4, 6} }; there’s a space on either side of the comma (so, 2 total) and, as a result, each bracketted set of values has 2 values. So, the number of values within each set of brackets is equal to the number of COLUMN in the table.
• Within int[ , ] someNums = { {2, 3}, {5, 6}, {4, 6} }; the first set of bracketted values goes in the first row, with the first value going in the first column, and the second value going in the second column. The second set of bracketted values goes in the second row, with the first value going in the first column, and the second value going in the second column. Finally, the third set of bracketted values goes in the third row, with the first value going in the first column, and the second value going in the second column.

I’ll now keep my eyes away from the result of running the code above, and create a table, and place the values, based on my new knowledge:

OK, so I got that right. Therefore, the code someNums[2, 0] means get the value from the multidimensional array called someNums from the intersection of index row 2, which is row 3, and index column 0, which is column 1. I’ll modify the table to reflect this as well:

So someNums[2, 0] has the value of 4 (which, incidentally, is correct).

Now, I’ll jump back to the code that lays out the numbers in a table, to see how it works:

`for (int k = 0; k < 3; k++) {     for (int j = 0; j < 2; j++) {          Console.Write(someNums[k, j] + “ “);     }     Console.WriteLine()}`
• In the first for loop, a variable is declared called k, with the data type integer, and an initial value of 0.
• Next, in the second for loop, a variable is declared called j, with the data type integer, and an initial value of 0.

Within that second for loop, the someNums[k, j] is the equivalent of:

• someNums[index row 0, index column 0], or
• someNums[row 1, column 1], or
• Within the array called someNums, the value at the intersection of the first row and the first column, which is 2.
• So, “2” is printed to the screen, followed by a space, and remains on the same line.
• The value of j is incremented from 0 to 1, and the check is run of whether j is less than 2, or is 1 less than 2?
• Since it is, the next line, someNums[k, j] is executed, which is someNums[0, 1], which is equal to 3.
• So, “3” is printed to the screen, followed by a space, and remains on the same line.
• The value of j is incremented from 1 to 2, and the check is run of whether j is less than 2, or is 2 less than 2?
• Since it isn’t, the for loop is exited and the next line, Console.WriteLine(); is executed, which simply places the cursor on the next line.
• The value of k is incremented from 0 to 1, and the check is run of whether k is less than 3, or is 1 less than 3?
• Since it is, the inner for loop is run again with the value of k at 1, and the value of j set as 0 again. That is, what is the value at the intersection of row 2 and column 1?
• That value is 5, which is printed to the screen.

The code continues as described going to the value at the intersection of row 2 and column 2, which is 6, followed by the value at the intersection of row 3 and column 1, which is 4, and, finally, the value at the intersection of row 3 and column 2, which is 6.

This really needed to be drawn out for me to understand it. My guess is that for most multidimensional arrays going forward, I’ll need to sketch it out to be able to visualize it (versus trying to see it in my head).

Anyway, I’m going to end this article here, and then follow it up with a second part where we’ll go over:

• Jagged Arrays — which are arrays of arrays (I’m sure that won’t give me a headache!)
• Array Properties & Methods — which you can use to get specific information about an array, or use some built-in array functionality.
• Working with Strings — which, similar to the previous item, let’s you retrieve specific information about a particular string object (yup, that says object), as well as some built-in string functionality.

As usual, feel free to correct, or comment on, anything I discussed and, here’s a link to the previous article, Learning to Code — Part 6: Classes & Objects.