Derived Types: Arrays

Initializing Arrays

int array1[4] = {0,1,2,3};

int array2[4] = {0,1,2};

int array3[1000] = {0};

int array4[] = {0,1,2,3};

char word[] = "Hello";

int scores[3][5] = {
{92,73,57,98,89},
{88,34,65,32,56},
{94,5,67,0,78,45}
};

int scores[][] = {
{92,73,57,98,89},
{88,34,65,32,56},
{94,5,67,0,78,45}
};

Using Arrays

Example 01:
#include
int main()
{
int test_index, student_index, scores[3][5] = {
{ 92 , 73 , 57 , 98 , 89 },
{ 88 , 76 , 23 , 95 , 72 },
{ 94 , 82 , 63 , 99 , 94 }
};
float sum;
for (test_index = 0; test_index < 3; test_index++){
for (student_index = 0, sum = 0; student_index < 5; student_index++)
sum = sum + scores[test_index][student_index];
cout << "Average for test" << test_index + 1 << " is " << sum / 5 << endl;
}
return 0;
}

Example 02:
#include
int main()
{
int scores[5];
scores[0] = 91;
scores[1] = 21;
scores[2] = 41;
scores[3] = 81;
scores[4] = 91;
cout<<"The score of the third person is "< return 0;
}

Determining The Size of An Array

We can use the sizeof operator to find the size of a one-dimensional array, because sizeof will tell us both the total size of the array in bytes and the size of each element in the array and all we have to do is to divide one by the other.

Example:
#include
int main()
{
int scores[5] = {92 , 73 , 57 , 98 , 89 };
cout << "The array is " << sizeof(scores) << " bytes long." << endl;
cout << "The array has " << sizeof(scores) / sizeof(int) << " elements.";
return 0;
}

Output:
The array is 10 bytes long.
The array has 5 elements.