array
array
In C++, an array is a data structure that is used to store multiple values of similar
data types in a contiguous memory location.
For example, if we have to store the marks of 4 or 5 students then we can easily
store them by creating 5 different variables but what if we want to store marks of
100 students or say 500 students then it becomes very challenging to create that
numbers of variable and manage them. Now, arrays come into the picture that can
do it easily by just creating an array of the required size.
o Fixed size
Example
int arr[5];
Here,
int: It is the type of data to be stored in the array. We can also use other
data types such as char, float, and double.
arr: It is the name of the array.
5: It is the size of the array which means only 5 elements can be stored
in the array.
Initialization of Array in C++
In C++, we can initialize an array in many ways but we will discuss some most
common ways to initialize an array. We can initialize an array at the time of
declaration or after declaration.
intarr[3];
return0;
}
Output
arr[0]: 10
arr[1]: 20
arr[2]: 30
intmain()
{
return0;
}
Output
2 4 6 8 10 12 14 16 18 20
Example 3: The C++ Program to Illustrate How to Find the Size of an Array
intmain()
{
intarr[] = { 1, 2, 3, 4, 5 };
// Length of an array
intn = sizeof(arr) / sizeof(arr[0]);
return0;
}
Output
Size of arr[0]: 4
Size of arr: 20//int data type size is 4byte then arr size is 20 because used int data
type of array.
Length of an array: 5
intmain()
{
// Declaring 2D array
intarr[4][4];
return0;
}
Output
0123
1234
2345
3456
Explanation
In the above code we have declared a 2D array with 4 rows and 4 columns after
that we initialized the array with the value of (i+j) in every iteration of the loop. Then
we are printing the 2D array using a nested loop and we can see in the below
output that there are 4 rows and 4 columns.
Example
int array[3][3][3];
intmain()
{
// declaring 3d array
intarr[3][3][3];
// initializing the array
for(inti = 0; i < 3; i++) {
for(intj = 0; j < 3; j++) {
for(intk = 0; k < 3; k++) {
arr[i][j][k] = i + j + k;
}
}
}
// printing the array
for(inti = 0; i < 3; i++) {
cout << i <<"st layer:"<< endl;
for(intj = 0; j < 3; j++) {
for(intk = 0; k < 3; k++) {
cout << arr[i][j][k] <<" ";
}
cout << endl;
}
cout << endl;
}
return0;
}
Output
0st layer:
012
123
234
1st layer:
123
234
345
2st layer:
234
345
456