C++ Code Example: Print Array Elements

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.

First Option

#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;
    }
}
Output
2
6
4
8
1

Second Option

#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;
    }
}
Output
Length of array: 5
2
6
4
8
1

Detailed Explanation

Array Declaration:

int numbers[] = {2, 6, 4, 8, 1};
  • This declares and initializes an array of integers named 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.
  • The difference between these two pointers (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;
  • This line prints the length of the array to the console. 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;
    }
  • This for loop iterates from 0 to arrayLength - 1.
  • In each iteration, numbers[i] accesses the ith element of the array.
  • cout << numbers[i] << endl; prints each element followed by a newline.

Summary

  • The code initializes an array with five integers.
  • It calculates the length of the array using the begin and end functions.
  • It prints the length of the array.
  • It iterates through the array and prints each element.