Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays November 8, 2017.

Similar presentations


Presentation on theme: "Arrays November 8, 2017."— Presentation transcript:

1 Arrays November 8, 2017

2 Arrays An array (also known as a list) is essentially a collection of variables of the same type. These variables are known as the elements of the array. int score[5]; declares an array of type int with five values. This is equivalent to int score_1, score_2, score_3, score_4, score_5; The elements in the array are numbered beginning with index 0, not 1! N.B. On the AP exam, all lists begin with index 1.

3 Array Elements To refer to a specific element in the array, place its index in brackets. score[0] refers to the first element, score[1] refers to the second, and so on until score[4], the last element. Important: If we declare an array of size n, the indices of the elements range from 0 to n – 1! Remember: on the AP exam, indices start at 1, so an array of size n has indices ranging from 1 to n.

4 Initializing Arrays An array can be initialized when it is declared. Consider the following code: int scores[3] = {2, 12, 1}; This is equivalent to the following: int scores[3]; scores[0] = 2; scores[1] = 12; scores[2] = 1;

5 Initializing Arrays If you list fewer values than the total number, the remaining values will be initialized to 0 of the array type. int array[3] = {1, 2}; //array is {1, 2, 0} double array[3] = {1.5, 2.5}; //array is {1.5, 2.5, 0} char array[3] = {'a', 'b'}; //array is {a, b, null} string array[3] = {"a", "b"}; //array is {a, b, null}

6 Initializing Arrays If an array is initialized when it is declared, the size can be omitted—it will be given the minimum size required to store the given elements. The following declarations are equivalent: int a[] = {1, 2, 3}; int a[3] = {1, 2, 3};

7 Array Practice What is the output of the following code?
char symbol[3] = {'a', 'b', 'c'}; for(int index = 0; index < 3; index++) { cout << symbol[index]; }

8 Array Practice What is the output of the following code?
int a[3] = {1, 2, 3}; a[1] = a[2]; cout << a[0] << " " << a[1] << " " << a[2] << endl;

9 Array Practice What is the output of the following code?
int i, temp[10]; for(i = 0; i < 10; i++) { temp[i] = 2 * i; } cout << temp[i] << " ";

10 Array Practice What is the output of the following code?
int i, temp[10] = {0}; for(i = 0; i < 10; i = i + 2) { temp[i] = 2 * i; } for(i = 0; i < 10; i++) cout << temp[i] << " ";


Download ppt "Arrays November 8, 2017."

Similar presentations


Ads by Google