C: More Operators and Arrays - Arrays
(Page 3 of 5 )
If we think of variables as a file folder, then we would think of an array as a file cabinet, capable of holding not just one value, but many. They operate in much the same fashion as variables, with a few exceptions. They still must be declared and given a type. Here is an example of how to declare an array and assign it some values:
To declare an array:
int mytestscores[5];
The above code declares an array with the data-type of an integer, names it mytestscores, and sets it to hold six elements, or values. You will note that the [5] portion is where we declare how many elements are in the array. I know what you're thinking: "but you said there were six elements!" There are. In programming languages, elements start off in the 0 position, so our element index (or where each piece of data would be stored) is: 0, 1, 2, 3, 4, 5.
Let's say we want to store my last six test scores at the same time we declare the array. Here is how we would do so:
int mytestscores[5]={100, 99, 98, 97, 96, 95}
Now let's say we wanted to assign a variable one of the values in our array. This is where the indexing will start to make sense:
int myworstscore;
myworstscore=mytestscores[5];
The above code creates a variable with the data-type of integer named myworstscore. It then assigns a value to the variable by calling upon an element in our mytestscores array, specifically, the value at index 5. In this case, 95.
We can also assign values to our array in the following manner:
int mytestscores[5];
mytestscores[0] = 100;
mytestscores[1] = 99;
mytestscores[2] = 98;
mytestscores[3] = 97;
mytestscores[4] = 96;
mytestscores[5] = 95;
Next: Two-Dimensional Arrays >>
More BrainDump Articles
More By James Payne