OneBite.Dev - Coding blog in a bite size

Iterate Over An Array In C++

Code snippet for how to Iterate Over An Array In C++ with sample and detail explanation

Iterating over an array in C++ is a fundamental practice that every programmer must familiarize themselves with. This article will provide a comprehensive guide to doing this properly, complete with a code snippet and thorough explanation.

Code Snippet: Iterating Over An Array in C++

Here’s a simple code snippet showing how to iterate over an array in C++:

#include <iostream>
using namespace std;

int main() {
    int arr[] = {10, 20, 30, 40, 50};

    for(int i=0; i<5; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

Code Explanation: Iterating Over An Array in C++

Let’s break down the code step by step.

Firstly, we included the iostream library which provides us IO functions. The “using namespace std;” line allows us to use elements of the standard (std) library, such as cout, directly.

int arr[] = {10, 20, 30, 40, 50};

Here, we’ve defined an integer array named ‘arr’ with five elements. These elements are ‘10, 20, 30, 40, 50’ respectively.

for(int i=0; i<5; i++) {
    cout << arr[i] << " ";
}

In this piece of code, we’ve implemented a ‘for loop’ to iterate over the elements of the array. The variable ‘i’ is first initialized to 0. Then the loop runs until ‘i’ is less than 5 (that is, the number of elements in the array). On each iteration, it increments ‘i’ by 1.

So in the first loop iteration, ‘i’ is 0. The statement cout << arr[i] << " "; prints the 0th element (first element) of the array on the console. In the second loop iteration, ‘i’ is 1, and it prints the 1st element (second element) of the array. The process continues until all elements are printed.

return 0;

This line of code signifies the successful completion of the main function (the starting point of our program).

In summary, this simple C++ program shows you one of the ways of how you can iterate over an array in C++. Going forward, you can modify and build upon this code snippet to work with arrays in more complex scenarios.

c-plus-plus