for loop and nested for loop in C++

The for loop is one of the three fundamental looping statements provided by c++. The for loop is more structured than its other counterparts. In this article, we shall see about some basic principles of for loop.

The syntax for the for loop is:

for(initialization;condition;update statement)

The variable to be used in looping conditions is created in the initialization statement.

The condition statement is a statement that returns a Boolean value. Every time before the loop is executed, the condition is checked. The loop stops its execution when the condition is false.

The update statement is executed every time when one iteration of the loop ends. It usually updates the variable initialized in the loop initialization statement.

C++ for loop example

The following example illustrates the working of for loop:
Suppose it is required to print first n numbers (where isĀ  taken as input from the user), This problem is easily solvable using for loop and the following code illustrates this

#include <iostream>

int main() {
    
    int n;
    std::cin>>n;
    for(int i=1;i<=n;i++) //i is the initialization variable, 
    {
        std::cout<<i<<" ";
    }
    return 0;
}
Output:
10
1 2 3 4 5 6 7 8 9 10

Here, the loop variable is incremented after each iteration by the update statement, and the loop body prints the numbers one by one.

Nested for loop:

The for loop can also contain another for loop whose initialization and conditions may or may not depend on the outer loop. The inner loop executes completely for each iteration of the outer loop. This can be explained well with an example.

Suppose we want a print a pyramid of numbers where the first row contains one and the second contains one and two and so on.
The output looks like this for case five
1
12
123
1234
12345

These can be easily generated from nestedĀ  for loops as follows:

#include <iostream>

int main() {
    
    int n;
    std::cin>>n;
    for(int i=1;i<=n;i++) //i is the initialization variable, 
    {
        for(int j=1;j<=i;j++)
        {
            std::cout<<j<<" ";
        }
        std::cout<<std::endl;
    }
    return 0;
}
Output:
7
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
1 2 3 4 5 6 
1 2 3 4 5 6 7

Checkout the following article to learn more about for loops
Looping through elements in an array

Leave a Reply

Your email address will not be published. Required fields are marked *