0
0
C++programming~10 mins

Array traversal in C++ - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Array traversal
Start at index 0
Check: index < array_size?
NoEXIT
Yes
Access array[index
Process element
Increment index
Back to Check
We start at the first element (index 0), check if the index is within the array size, process the element, then move to the next index until we reach the end.
Execution Sample
C++
#include <iostream>
using namespace std;

int main() {
    int arr[] = {10, 20, 30};
    int n = 3;
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}
This code prints each element of the array one by one.
Execution Table
IterationiCondition (i < n)ActionOutput
10TruePrint arr[0] = 1010
21TruePrint arr[1] = 2020
32TruePrint arr[2] = 3030
43FalseExit loop
💡 i reaches 3, condition 3 < 3 is False, loop ends
Variable Tracker
VariableStartAfter 1After 2After 3Final
iundefined0123
Output"""10 ""10 20 ""10 20 30 ""10 20 30 "
Key Moments - 3 Insights
Why does the loop stop when i equals the array size?
Because the condition i < n becomes false at i = 3 (array size), so the loop exits as shown in execution_table row 4.
Why do we start indexing from 0 instead of 1?
Arrays in C++ start at index 0, so the first element is arr[0]. This is why the loop starts with i = 0 (execution_table row 1).
What happens if we try to access arr[i] when i >= n?
Accessing arr[i] when i >= n causes undefined behavior (out of bounds). The loop condition prevents this by stopping before i reaches n (see exit condition in execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i during the third iteration?
A1
B2
C3
D0
💡 Hint
Check the 'i' column in the third row of the execution_table.
At which iteration does the loop condition become false?
AIteration 4
BIteration 3
CIteration 2
DIteration 1
💡 Hint
Look at the 'Condition (i < n)' column where it becomes False in the execution_table.
If the array size n was 4 instead of 3, how many times would the loop run?
A5 times
B3 times
C4 times
D2 times
💡 Hint
The loop runs while i < n, so if n=4, it runs for i=0,1,2,3 (4 times).
Concept Snapshot
Array traversal in C++:
Use a for loop from i = 0 to i < array_size.
Access elements with arr[i].
Loop stops before i reaches array_size to avoid out-of-bounds.
Print or process each element inside the loop.
Full Transcript
This example shows how to traverse an array in C++. We start with index i at 0, check if i is less than the array size n, then access and print the element at arr[i]. After processing, we increase i by 1 and repeat. The loop stops when i equals n, preventing out-of-bounds access. The output prints each element separated by spaces.