This program demonstrates how to print the elements of an array in C++. The array numbers
is defined with 5 elements of integers. The length of the array is calculated by dividing the size of the whole array with the size of a single element of the array. The result of this division is stored in the variable arrayLength
.
The for loop then iterates arrayLength
times, and for each iteration, it prints the element of the numbers
array at the current index (i.e., numbers[i]
) followed by a new line character.
#include <iostream>
using namespace std;
int main () {
int numbers[] = {2, 6, 4, 8, 1};
int arrayLength = sizeof numbers / sizeof numbers[0];
for(int i = 0; i < arrayLength; i++) {
cout << numbers[i] << endl;
}
}
2
6
4
8
1
#include <iostream>
using namespace std;
int main () {
int numbers[] = {2, 6, 4, 8, 1};
int arrayLength = end(numbers) - begin(numbers);
cout << "Length of array: " << arrayLength << endl;
for(int i = 0; i < arrayLength; i++) {
cout << numbers[i] << endl;
}
}
Length of array: 5
2
6
4
8
1