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

The program initializes an integer array myArray with 8 elements, and then calculates its length by dividing the total size of the array in bytes by the size of an individual element.

The program then initializes a counter variable i to 0 and enters a while loop. The loop iterates as long as i is less than the length of the array.

Inside the loop, the program prints out the element at the current index of the array (myArray[i]) and then increments the counter i.

Once i is equal to the length of the array, the loop terminates and the program exits.

#include <iostream>
using namespace std;

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

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