Loops In C++

In C++, loops are control statements and are used to execute a block of code repeatedly as long as a specified condition is true. There are several types of loops available in C++, including the for loop, the while loop, and the do-while loop. Each type of loop has its own syntax and use cases.

There are 3 types of loops in C++:-

  • for loop
  • while loop
  • do-while loop

for loop

The for loop is commonly used when you know the exact number of iterations you want to perform. It consists of three parts: initialization, condition, and increment/decrement.

Here's the syntax:

for (initialization; condition; increment/decrement) {
    // code to be executed
}

Here,

  • Initialization: Typically used to initialize a loop control variable. It's executed only once, at the beginning of the loop.

  • Condition: An expression evaluated before each iteration. If the condition is true, the loop continues; otherwise, the loop terminates.

  • Increment/Decrement: Usually used to modify the loop control variable. It's executed after each iteration.

    For Loop

Example:-

#include <iostream>
using namespace std;
 
int main() {
    for (int i = 1; i <= 7; ++i) {
        cout << i << " ";
    }
    return 0;
}

Output:-

1 2 3 4 5 6 7

Explanation:-

IterationVariableiAction
1sti = 1true1 is printed. i is increased to 2
2ndi = 2true2 is printed. i is increased to 3
3rdi = 3true3 is printed. i is increased to 4
4thi = 4true4 is printed. i is increased to 5
5thi = 5true5 is printed. i is increased to 6
6thi = 6true6 is printed. i is increased to 7
7thi = 7true7 is printed. i is increased to 8
8thi = 8falseThe loop is terminated

Ranged Based for Loop

The range-based for loop is a convenient feature introduced in C++11, which simplifies iteration over elements in a container, such as arrays, vectors, and other sequence-like data structures.

Here's the syntax of the range-based for loop:-

for (declaration : range) {
    // code to be executed
}
  • declaration: A variable that will be declared for each iteration, representing the current element in the range.
  • range: The range over which to iterate. It can be an array, a container (such as vector, list, etc.), or any sequence-like data structure that provides a begin and end iterator.

Here's an example to illustrate the usage of the range-based for loop:-

#include <iostream>
using namespace std;
 
int main() {
  
    int num_array[] = {1, 2, 3, 4, 5, 6, 7};
  
    for (int n : num_array) {
        cout << n << " ";
    }
  
    return 0;
}

Output:-

1 2 3 4 5 6 7

while loop

A while loop is a control flow statement in C++ that allows you to execute a block of code repeatedly as long as a specified condition is true. It's useful when you don't know the exact number of iterations beforehand and want to continue looping until a certain condition is met.

Here's the basic structure of a while loop:-

while (condition) {
    // code to be executed
}

Explanation:-

  • Condition: The loop continues to execute as long as the specified condition evaluates to true. If the condition evaluates to false, the loop terminates, and program control moves to the next statement after the loop.

  • Code Block: The code block inside the loop is executed repeatedly as long as the condition remains true. It contains the statements that you want to repeat.

    While Loop

Example Code:

Here's a simple example of a while loop in C++ that prints numbers from 1 to 5:-

#include <iostream>
using namespace std;
 
int main() {
    int i = 1;  // Initialize loop control variable
 
    // While loop to print numbers from 1 to 5
    while (i <= 5) {
        cout << i << " ";  // Print the current value of i
        i++;  // Increment i for the next iteration
    }
 
    return 0;
}

Output:

1 2 3 4 5

Explanation of the Code:-

IterationVariableiAction
1sti = 1true1 is printed. i is increased to 2
2ndi = 2true2 is printed. i is increased to 3
3rdi = 3true3 is printed. i is increased to 4
4thi = 4true4 is printed. i is increased to 5
5thi = 5true5 is printed. i is increased to 6
6thi = 6falseThe loop is terminated

do-while loop

The do-while loop is another type of loop in C++ that is similar to the while loop. However, the difference lies in when the loop condition is evaluated. In a do-while loop, the condition is evaluated after the loop body is executed, meaning that the loop body will always execute at least once, even if the condition is initially false.

Here's the basic syntax of a do-while loop:-

do {
    // code to be executed
} while (condition);

Explanation:

  • Code Block: The block of code inside the do-while loop is executed first.

  • Condition: After executing the loop body, the condition is evaluated. If the condition is true, the loop continues, and the code block is executed again. If the condition is false, the loop terminates.

    Do While Loop

Example Code:

Let's see an example of a do-while loop in C++ that prints numbers from 1 to 5:-

#include <iostream>
using namespace std;
 
int main() {
    int i = 1;  // Initialize loop control variable
 
    // Do-while loop to print numbers from 1 to 5
    do {
        cout << i << " ";  // Print the current value of i
        i++;  // Increment i for the next iteration
    } while (i <= 5);
 
    return 0;
}

Output:

When you run the above code, it will print:

1 2 3 4 5

Explanation of the Code:-

IterationVariablei <= 5Action
1sti = 1not checked1 is printed. i is increased to 2
2ndi = 2true2 is printed. i is increased to 3
3rdi = 3true3 is printed. i is increased to 4
4thi = 4true4 is printed. i is increased to 5
5thi = 5true5 is printed. i is increased to 6
6thi = 6falseThe loop is terminated

Infinite loop

An infinite loop is a loop that continues indefinitely, executing its block of code repeatedly without stopping.

Here's an example of an infinite for loop in C++:

#include <iostream>
using namespace std;
 
int main() {
    // Infinite for loop
    for (;;) {
        cout << "This is an infinite loop." << endl;
    }
 
    return 0;
}
  • The for loop has no initialization, condition, or increment/decrement expressions specified inside the parentheses.
  • Therefore, the loop will continue indefinitely, repeatedly printing "This is an infinite loop." to the console.

An infinite while loop can be created by specifying a condition that always evaluates to true. Here's an example:

#include <iostream>
using namespace std;
 
int main() {
    while (true) {
        cout << "This is an infinite loop." << endl;
    }
 
    return 0;
}

An infinite do-while loop can be created similarly by specifying a condition that always evaluates to true. Here's an example:

#include <iostream>
using namespace std;
 
int main() {
    do {
        cout << "This is an infinite loop." << endl;
    } while (true);
 
    return 0;
}
  • Since the condition is always true, the while and do-while loop continues to execute indefinitely, repeatedly printing "This is an infinite loop." to the console.

It's essential to exercise caution when using infinite loops because they can lead to programs becoming unresponsive or consuming excessive resources. In practice, infinite loops are often used in conjunction with some kind of termination condition, such as a break statement or an external event that causes the loop to exit. Without a termination condition, the loop will continue indefinitely, which may not be desirable in most situations.

Nested Loops

Topic asked in December 2022 (CBCS) question paper.

Nested loops in C++ refer to the situation where one loop is nested inside another loop. This allows you to iterate over a two-dimensional structure, such as a matrix or a grid, by using an outer loop to iterate over the rows and an inner loop to iterate over the columns (or vice versa).

Here's the general syntax of nested loops:-

for loop:-

for (initialization; condition; increment/decrement) {
    for (initialization; condition; increment/decrement) {
        // code to be executed
    }
}

Or with while loop:-

while (condition) {
    while (condition) {
        // code to be executed
    }
}

Or with do-while loops:-

do {
    do {
        // code to be executed
    } while (condition);
} while (condition);

Example:

#include <iostream>
using namespace std;
 
int main() {
    // Outer loop to iterate over rows
    for (int i = 0; i < 5; ++i) {
        // Inner loop to iterate over columns
        for (int j = 0; j < 5; ++j) {
            cout << "* ";
        }
        cout << endl; // Move to the next row after printing all columns
    }
 
    return 0;
}

Output:-

* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

In this example:-

  • The outer loop for (int i = 0; i < 5; ++i) iterates over the rows (i represents the row index).
  • The inner loop for (int j = 0; j < 5; ++j) iterates over the columns within each row (j represents the column index).
  • Inside the inner loop, we print an asterisk followed by a space.
  • After printing all columns in a row, we move to the next line cout << endl;, effectively printing each row on a new line.

Checkout another example program of nesting of loops.

Difference between for, while and do-while loop

Featurefor Loopwhile Loopdo-while Loop
InitializationInitialization statement is included within the loop syntaxInitialization statement is done before the loop startsInitialization statement is done before the loop starts
Condition CheckingCondition is checked before each iterationCondition is checked before each iterationCondition is checked after each iteration
IterationIncrement/decrement operation is often included within the loop syntaxIncrement/decrement operation must be done explicitly within the loop bodyIncrement/decrement operation must be done explicitly within the loop body
UsagePreferred when the number of iterations is known beforehand or when iterating over a rangePreferred when the loop may not be executed at all or when the number of iterations is unknownPreferred when the loop must execute at least once before condition checking

Break And Continue Statements

Break Statements

Topic asked in July 2022 (CBCS) question paper.

The break statement is a control flow statement used in loops (such as for, while, or do-while loops) to prematurely exit the loop's execution when a certain condition is met. When encountered, the break statement causes immediate termination of the loop containing it, and program execution continues with the statement following the loop.

Example:-

#include <iostream>
using namespace std;
 
int main() {
    // Using break in a for loop
    for (int i = 1; i <= 5; ++i) {
        cout << i << " ";
        if (i == 3) {
            break;  // Exit the loop when i equals 3
        }
    }
    cout << endl;
    cout << "Loop terminated." << endl;
 
    return 0;
}

Output:-

1 2 3 
Loop terminated.

Explanation:-

  • The for loop iterates from 1 to 5.
  • Inside the loop, each value of i is printed followed by a space.
  • When i equals 3, the condition if (i == 3) is true, and the break statement is executed, causing immediate termination of the loop.
  • As a result, only the numbers 1, 2, and 3 are printed, and the message "Loop terminated." is displayed.

We can also use break statement with nested loop:-

#include <iostream>
using namespace std;
 
int main() {
    // Two loops with termination condition in the nested loop
    for (int i = 1; i <= 3; ++i) {
        cout << "Outer loop iteration: " << i << endl;
        for (int j = 1; j <= 3; ++j) {
            cout << "Inner loop iteration: " << j << endl;
            if (j == 3) {
                break; // Exit the inner loop when j equals 3
            }
        }
    }
 
    return 0;
}

Output:-

Outer loop iteration: 1
Inner loop iteration: 1
Inner loop iteration: 2
Outer loop iteration: 2
Inner loop iteration: 1
Inner loop iteration: 2
Outer loop iteration: 3
Inner loop iteration: 1
Inner loop iteration: 2

Explanation:-

  • The outer loop iterates from 1 to 3.
  • The inner loop iterates from 1 to 3.
  • When the condition j == 3 is met in the inner loop, the break statement is executed, causing immediate termination of the inner loop.

We can also use break statement in while and do-while loop:-

Example with break in a while Loop:

#include <iostream>
using namespace std;
 
int main() {
    int i = 1;
 
    // Using break in a while loop
    while (true) {
        cout << i << " ";
        if (i == 5) {
            break; // Exit the loop when i equals 5
        }
        i++;
    }
 
    cout << endl << "Loop terminated." << endl;
 
    return 0;
}

Output:-

1 2 3 4 5 
Loop terminated.

Example with break in a do-while Loop:

#include <iostream>
using namespace std;
 
int main() {
    int i = 1;
 
    // Using break in a do-while loop
    do {
        cout << i << " ";
        if (i == 5) {
            break; // Exit the loop when i equals 5
        }
        i++;
    } while (true);
 
    cout << endl << "Loop terminated." << endl;
 
    return 0;
}

Output:-

1 2 3 4 5 
Loop terminated.

In both examples:

  • The loop runs endlessly until the break condition is satisfied.
  • The break statement is used to exit the loop when i equals 5.
  • Once the break statement is encountered, the loop immediately terminates, and program execution continues with the statement following the loop.

Continue Statements

The continue statement is another control flow statement used in loops to skip the rest of the current iteration and proceed with the next iteration of the loop. When encountered, the continue statement causes the loop to jump immediately to the next iteration, bypassing any remaining code in the loop body for the current iteration.

Example:-

#include <iostream>
using namespace std;
 
int main() {
    // Using continue in a for loop
    for (int i = 1; i <= 5; ++i) {
        if (i == 3) {
            continue;  // Skip iteration when i equals 3
        }
        cout << i << " ";
    }
    cout << endl;
    cout << "Loop completed." << endl;
 
    return 0;
}

Output:-

1 2 4 5 
Loop completed.

Explanation:-

  • The continue statement is used to skip the iteration when i equals 3.
  • As a result, the number 3 is skipped, and only the numbers 1, 2, 4, and 5 are printed.

We can also use the continue statement with nested loops:

#include <iostream>
using namespace std;
 
int main() {
    // Two loops with termination condition in the nested loop
    for (int i = 1; i <= 3; ++i) {
        cout << "Outer loop iteration: " << i << endl;
        for (int j = 1; j <= 3; ++j) {
            cout << "Inner loop iteration: " << j << endl;
            if (j == 3) {
                continue; // Skip the current iteration of the inner loop when j equals 3
            }
        }
    }
 
    return 0;
}

Output:-

Outer loop iteration: 1
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Outer loop iteration: 2
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Outer loop iteration: 3
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3

Explanation:-

  • The outer loop iterates from 1 to 3.
  • The inner loop iterates from 1 to 3.
  • When the condition j == 3 is met in the inner loop, the continue statement is executed, causing the current iteration of the inner loop to be skipped.

We can also use the continue statement in while and do-while loops:

Example with continue in a while Loop:

#include <iostream>
using namespace std;
 
int main() {
    int i = 0;
 
    // Using continue in a while loop
    while (i < 5) {
        i++;
        if (i == 3) {
            continue; // Skip the current iteration when i equals 3
        }
        cout << i << " ";
    }
 
    cout << endl << "Loop completed." << endl;
 
    return 0;
}

Ouput:-

1 2 4 5 
Loop completed.

Example with continue in a do-while Loop:

#include <iostream>
using namespace std;
 
int main() {
    int i = 0;
 
    // Using continue in a do-while loop
    do {
        i++;
        if (i == 3) {
            continue; // Skip the current iteration when i equals 3
        }
        cout << i << " ";
    } while (i < 5);
 
    cout << endl << "Loop completed." << endl;
 
    return 0;
}

Output:-

1 2 4 5 
Loop completed.

In both examples:

  • The loop iterates until the condition is satisfied.
  • The continue statement is used to skip the current iteration when a certain condition is met.
  • As a result, the number 3 is skipped in both loops.
How's article quality?

Last updated on -

Page Contents