Arrays

Sometimes, we want to store many values inside of one Variable. An Array is a variable that can store many values. You can think about an Array as a list. Here's an example of two ways we can make an array:

``````int arr[] = {34, 1, 180, 92, 17, 17, 0, 12};
OR
int arr[8];
arr = {34, 1, 180, 92, 17, 17, 0, 12};
``````
01234567
341180921717012

Each value has an Index, a numbered location in the Array. Here's an example of how we could change one of the values in the Array:

``````arr[3] = 5; //Changes 92 to 5
``````
01234567
34118051717012

Strings

So what happens if we make an Array of Characters? We call it a String! This is important: String is not a Primitive Data Type (like `int`, `char`, `float`), it is simply an Array made from Characters. Because we use Strings so much, C makes it easy to use strings by letting us put them in double quotes (").

``````char name[8] = "Chris";
OR
char name[8] = {'C', 'h', 'r', 'i', 's'};
``````
01234567
'C''h''r''i''s''\0''\0''\0'

The NULL Character `'\0'` indicates that there is nothing stored in index 5, 6 and 7. Every String must end with a NULL Character.

Using For Loops with Arrays

`for` Loops are the Right Tool For The Job when you want to do something to every item in the array:

2D Arrays

So if Strings are Arrays of Characters, then an Array of Strings is an Array of Arrays of Characters... Can we do that?

Yes! An "Array of Arrays" is sometimes called a 2-Dimensional Array (or 2D Array) because it takes 2 Dimensions to show what it looks like. Here's an example of a 2D Array:

``````int arr[][] = { {13, 44, 82, 1},
{22, 11, 90, 62}
{10, 15, 4, 7} };
``````
0123
01344821
122119062
2101547

And here's how we could change one value inside of it:

``````arr[1][2] = 33; //Changes 90 to 33
``````
0123
01344821
122113362
2101547

2D arrays are a good way to store strings. Here's an example:

``````char names[3][1000];
strcpy(names[0], "John");
strcpy(names[1], "Malik");
strcpy(names[2], "Tan");
``````
 0 1 2 3 0 1 4 ... 999 'J' 'o' 'h' 'n' '\0' ... '\0' 'M' 'a' 'l' 'i' 'k' ... '\0' 'T' 'a' 'n' '\0' '\0' ... '\0'