The Wayback Machine - https://web.archive.org/web/20250310171533/https://www.geeksforgeeks.org/cpp-loops/
Open In App

C++ Loops

Last Updated : 16 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print “Hello World” 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.

C++
#include <iostream>
using namespace std;

int main() {
  
      // Print hello world 5 times
    cout << "Hello World\n";
    cout << "Hello World\n";
    cout << "Hello World\n";
    cout << "Hello World\n";
    cout << "Hello World\n";
    return 0;
}

Output
Hello World
Hello World
Hello World
Hello World
Hello World

Let’s say you have to write it 20 times (it would surely take more time to write 20 statements) now imagine you have to write it 100 times, it would be really hectic to re-write the same statement again and again. In this case, loops come into use allowing users to repeatedly execute a block of statements.

C++
#include <iostream>
using namespace std;

int main() {
  
      for (int i = 0; i < 5; i++) {
        cout << "Hello World\n";
    }
    return 0;
}

Output
Hello World
Hello World
Hello World
Hello World
Hello World

What are Loops?

In C++ programming, a loop is an instruction that is used to repeatedly execute a code until a certain condition is reached. They are useful for performing repetitive tasks without having to write the same code multiple times.

Loops can be classified on the basis of the sequency in which they check the condition relative to the execution of the associated block of code.

  1. Entry Controlled loops: In this type of loop, the test condition is tested before entering the loop body.
  2. Exit Controlled Loops: In this type of loop, the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false.

C++ provides three loops:

Let’s understand each of them in detail.

for Loop

A for loop is a repetition control structure that allows us to write a loop that is executed a specific number of times. It is an entry-controlled loop that enables us to perform n number of steps together in one line. 

Syntax

for (initialization; condition; updation) {
// body of for loop
}

The various parts of the for loop are:

  • Initialization: Initialize the loop variable to some initial value.
  • Test Condition: This specifies the test condition. If the condition evaluates to true, then body of the loop is executed, and loop variable is updated according to update expression. If evaluated false, loop is terminated.
  • Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value.

Example

C++
#include <iostream>
using namespace std;

int main() {
  
      // For loop that starts with i = 1 and ends
      // when i is greater than 5.
    for (int i = 1; i <= 5; i++) {
        cout << i << " ";
    }

    return 0;
}

Output
1 2 3 4 5 

Important Properties of for Loop

  • The initialization and updation statements can perform operations unrelated to the condition statement, or nothing at all – if you wish to do. But the good practice is to only perform operations directly relevant to the loop.
  • A variable declared in the initialization statement is visible only inside the scope of the for loop and will be released out of the loop.
  • Don’t forget that the variable which was declared in the initialization statement can be modified during the loop, as well as the variable checked in the condition.

Range Based for Loop

There is a type of for loop that does not need the condition and updation statement. It is called range based for loop and it can only be used for iteratable objects such as vector, set, etc. For a vector named v, it can be written to print its elements as:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v { 1, 2, 3, 4, 5};
    
      // Using range based for loop to print vector
      for (auto i: v) {
          cout << i << " ";
    }
      
    return 0;
}

Output
1 2 3 4 5 

while Loop

While studying for loop, we have seen that the number of iterations is known beforehand, i.e. the number of times the loop body is needed to be executed is known to us. while loop is used in situations where we do not know the exact number of iterations of the loop beforehand. It is an entry-controlled loop whose execution is terminated on the basis of the test conditions.

Syntax

while (condition) {
// Body of the loop
update expression
}

Only the condition is the part of while loop syntax, we have to do the initialization and updation manually outside and inside the loop respectively.

Example

C++
#include <iostream>
using namespace std;

int main() {
  
      // Initialization
      int i = 1;
  
      // while loop that starts with i = 1 and ends
      // when i is greater than 5.
    while (i <= 5) {
        cout << i << " ";
      
          // Updation
          i++;
    }

    return 0;
}

Output
1 2 3 4 5 

do while Loop

The do-while loop is also a loop whose execution is terminated on the basis of test conditions. The main difference between a do-while loop and the while loop is in the do-while loop the condition is tested at the end of the loop body, i.e. do-while loop is exit controlled whereas the other two loops are entry-controlled loops. So, in a do-while loop, the loop body will execute at least once irrespective of the test condition.

Syntax

do {
// Body of the loop
// Update expression
} while (condition);

Like while loop, only the condition is the part of do while loop syntax, we have to do the initialization and updation manually outside and inside the loop respectively.

Example

C++
#include <iostream>
using namespace std;

int main() {
  
      // Initialization
      int i = 1;
  
      // while loop that starts with i = 1 and ends
      // when i is greater than 5.
     do {
        cout << i << " ";
      
          // Updation
          i++;
    }while (i <= 5);

    return 0;
}

Output
1 2 3 4 5 

Remember the last semicolon at the end of the loop.

Infinite Loops

An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional exit so that it repeats indefinitely. An infinite loop occurs when a condition is always evaluated to be true. Usually, this is an error. We can manually create an infinite loop using all three loops:

Using for Loop

C++
#include <iostream>
using namespace std;

int main() {

    // This is an infinite for loop as the condition
    // expression is blank
    for (;;) {
        cout << "This loop will run forever.\n";
    }
    return 0;
}


Output

This loop will run forever.
This loop will run forever.
...................

Using while Loop

C++
#include <iostream>
using namespace std;

int main() {

    // This is an infinite while loop as the condition
    // expression is always true
    while(1) {
        cout << "This loop will run forever.\n";
    }
    return 0;
}


Output

This loop will run forever.
This loop will run forever.
...................

Using do while Loop

C++
#include <iostream>
using namespace std;

int main() {

    // This is an infinite do while loop as the condition
    // expression is always true
    do {
        cout << "This loop will run forever.\n";
    }while(1);
    return 0;
}


Output

This loop will run forever.
This loop will run forever.
...................


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg