C++ Code Example: for-loop through an array to output the content

In this code, the myArray variable is an array of integers that contains eight elements, which are initialized with the values {4, 8, 1, 56, 73, 36, 99, 21} using the initializer list syntax.

The myArrayLength variable is set to the length of the array using the sizeof operator, which returns the size of the array in bytes, and then dividing it by the size of an individual element in the array using the sizeof(*myArray) syntax.

Finally, a for loop is used to iterate over the elements of the myArray array and print each element to the console using the cout statement.

#include <iostream>
using namespace std;

int main() {
    int myArray[] = {4, 8, 1, 56, 73, 36, 99, 21};
    int myArrayLength = sizeof(myArray) / sizeof(*myArray);

    for (int i = 0; i < myArrayLength ; i++) {
        cout << myArray[i] << endl;
    }
}
Output
4
8
1
56
73
36
99
21