Arrays1 - Arrays What is it? An array is a data structure...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
Arrays What is it? An array is a data structure that holds a number of related variables. Thus, an array has a size which is the number of variables it can store. All of these variables must be of the same type. (In essence declaring an array allows you to use many variables of the same type without explicitly declaring all of them.) You can picture an array like below: Each cell of the array can hold one data item. Furthermore, each cell has its own index, to distinguish it from the rest of the cells. In C, these cells are always numbered from 0 to the size of the array minus one. Here is the generic syntax for an array declaration: type <var_name>[size]; For example to define an integer array called numbers of size 10, we would do the following: int numbers[10]; Note that the expression inside the brackets of an array declaration must evaluate to a constant. This is because the computer needs to know how much space to allocate for the array beforehand.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
To refer to a variable in a single cell or element of an array, you use the name of the array, followed by a bracket, the index you want to access, and then another bracket. Thus, numbers[0] = 3; would set the int variable in the 0 index of the array numbers to 3. A sample program The following program will read in five test scores and then print these out in reverse order: int main() { int index, test_scores[5]; // Read in scores into the array. printf("Please enter 5 test scores.\n"); for ( index=0; index < 5; index++) scanf ("%d", &test_scores[index]); // Print them out by going through the array in backwards. printf( "Here are the scores in reverse order: "); for ( index=4; index >= 0; index--) printf ("%d ", test_scores[index]); }
Background image of page 2
Common mistakes made with arrays 1. Out of Bounds error: This is when you index into an array with an invalid index. For example, if you declare an array as follows: int test_scores[5]; and tried to access test_scores[5] or test_scores[-1], you would be trying to access a variable that does not exist, since
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 10

Arrays1 - Arrays What is it? An array is a data structure...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online