4 Array
4 Array
Structure – I
PPT - IV
• For example,
• Suppose a class has 27 students, and we need to store the grades of all of them.
Instead of creating 27 separate variables, we can simply create an array:
double grade[27];
Here, grade is an array that can hold a maximum of 27 elements of double type. In
C++, the size and type of arrays cannot be changed after its declaration.
Basic Computer Programming By Prof. Nikita Khandelwal
C++ Array Declaration
dataType arrayName[arraySize];
For example,
int x[6];
Here,
• int - type of element to be stored
• x - name of the array
• 6 - size of the array
• The array indices start with 0. Meaning x[0] is the first element stored
at index 0.
• If the size of an array is n, the last element is stored at index (n-1). In
this example, x[5] is the last element.
• Elements of an array have consecutive addresses. For example,
suppose the starting address of x[0] is 2120d. Then, the address of the
next element x[1] will be 2124d, the address of x[2] will be 2128d and
so on.
Here, the size of each element is increased by 4. This is because the size
of int is 4 bytes.
Basic Computer Programming By Prof. Nikita Khandelwal
C++ Array Initialization
• In C++, it's possible to initialize an array during declaration. For example,
• // declare and initialize and array
• int x[6] = {19, 10, 8, 17, 9, 15};
#include <iostream>
using namespace std; cout << "\nTheir Sum = " << sum
int main() { << endl;
double numbers[] = {7, 5, 6, 12, 35, 27}; // find the average
double sum = 0; average = sum / count;
double count = 0; cout << "Their Average = " <<
average << endl;
double average;
return 0;
cout << "The numbers are: ";
}
for (const double &n : numbers) {
cout << n << " ";
sum += n;
++count;
} Basic Computer Programming By Prof. Nikita Khandelwal
Output
The numbers are: 7 5 6 12 35 27
Their Sum = 92
Their Average = 15.3333
float x[2][4][3];
2 x 4 x 3 = 24