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
Array Declaration:
int numbers[] = {2, 6, 4, 8, 1};
numbers with five elements: 2, 6, 4, 8, and 1.Calculating Array Length:
int arrayLength = end(numbers) - begin(numbers);
begin(numbers) returns a pointer to the first element of the array.end(numbers) returns a pointer to one past the last element of the array.end(numbers) - begin(numbers)) gives the number of elements in the array, which is stored in arrayLength.Printing Array Length:
cout << "Length of array: " << arrayLength << endl;
cout is the standard output stream, << is the stream insertion operator, and endl inserts a newline character and flushes the stream.Iterating Through the Array:
for(int i = 0; i < arrayLength; i++) {
cout << numbers[i] << endl;
}
for loop iterates from 0 to arrayLength - 1.numbers[i] accesses the ith element of the array.cout << numbers[i] << endl; prints each element followed by a newline.begin and end functions.