What are Loops in C++? 

In computer programming, a loop is used to achieve the task of executing a block of instructions multiple times. You can understand this with a very simple example.  Let’s say you want to print the statement “Welcome to C++ world!” a hundred times. One way of doing this would be to write the print statement 100 times, which is not practical. The other way is by using the loops. You can simply put the print statement into a loop, which runs and prints the message as output a hundred times. Loops make a program more readable and enhance its efficiency by simplifying complex tasks.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

C++ supports three types of loops:

  • for loop

  • while loop
  • do-while loop

In this article, you will learn what while loops in C++ are, compare them with other loops in C++, and discuss their advantages along with some examples.

What is a While Loop in C++?

A while loop in C++ is one of the three loops that are provided by C++. It is an entry-controlled loop that is best suited for cases where you are not sure about the exact number of iterations. The while loop works on a boolean condition that regulates the iteration of the loop. It terminates the loop once it violates the condition. Since it is an entry-controlled loop, this loop checks if the statement is satisfied or not at the entry of the loop.

Why Do You Need a While loop?

A loop is used when there is a need to execute a particular task “n” number of times. A while loop can be used in situations where there is an unknown number of iterations or the iterations are not fixed. A while loop in C++ is a pre-test or an entry-controlled loop, which means that it tests the boolean condition before it executes the statements inside the loop body. You will understand this better with some real-life examples.

  1. Let’s say you want to iterate over a collection of books. But the number of books is not known to you in advance. However, you want to run the loop until you iterate over all the books. In such a situation, you can use a while loop where you will have greater control over updating the iterating condition of the loop.  
  2. Another example is a music streaming application. The app plays a song until the user presses “pause” or “stop”. The execution statement here is to play the song. Here, the test condition is “user doesn’t press pause/stop OR not the end of playlist”. 

Syntax of While Loops in C++

The syntax of the while loop in C++ is:

while (test condition)

{

   // loop body

  update expression;

}

Parts of the while loop:

  • test condition: This is a boolean condition that tells the while loop when to stop. If this condition returns true, the loop keeps on executing. The loop terminates when this condition returns false.

Examples

i <= 5

head != NULL

arr[i] <= 2

  • update expression: This is an expression that is provided to update the loop variable. After the execution of all the statements inside the loop’s body, it updates the control variable at the end.

Examples

i++

i--

i /= 10

i *= 2

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

How Does a While Loop in C++ Work? 

The process of execution of a while loop is explained as follows:

STEP 1: The while loop gets control in the program

STEP 2: The control first goes to the test condition

STEP 3: It checks the test condition

  1. If the condition returns true, the while loop body gets executed
  2. If the condition returns false, the while loop gets terminated

STEP 4: It executes the while loop statements

STEP 5: After the execution, the control variable gets updated

STEP 6: The flow of control goes to STEP 2

STEP 7: The execution of the while loop ends

The following flowchart shows the execution of a while loop in C++:

While_Loop_In_C_Plus_Plus_1.

What is a do-while Loop in C+? 

The do-while is the third type of loop provided by C++. It is similar to the while loop in many aspects. Just like the while loop, the initialization statement takes place outside the do-while loop. And the loop termination takes place based on a conditional statement. But the main difference between both these loops is that the while loop is an entry controlled loop while the do-while loop is an exit controlled loop.

Entry-controlled loops are those in which the conditional statement is checked at the entry point, i.e., before the execution of the loop statement. Whereas, in the exit controlled loops, the conditional statement is checked after the loop statement is executed. Due to this, the exit controlled loops (do-while loop) execute at least one time, irrespective of the test statement.

Syntax

do

{

   // loop body

   increment/decrement;

while (condition statement);

Parts of the do-while loop in C++

  • test condition: This is a boolean condition that tells the while loop when to stop. This condition is checked at the end of the loop. This results in the execution of the code at least one time. If the condition is violated, the loop terminates.

  • update expression: This is an update expression that is provided to update the loop variable. This expression controls how the loop will iterate. The loop variable is updated after the execution of all the statements inside the loop’s body.

Below is a simple code explaining the implementation of the do-while loop:

#include <iostream>

using namespace std;

int main()

{

    // initialization expression

    int i = 1; 

     // print 5 multiples of 2

    do {

        cout << 2*i << endl;

        // update expression

        i++; 

    }

    // test condition

    while (i <= 5);  

    return 0;

}

While_Loop_In_C_Plus_Plus_2.

In the program depicted above, a do-while loop is used to print 5 multiples of 2. Since it is a do-while loop, it will be executed at least one time irrespective of what is returned by the test condition. So in any case, 2 will always be printed in this example. 

Nested while loop in C++ 

As the name suggests, Nested loops are loops within loops and hence are also known referred to as loop inside a loop. There can be one or more than one loop within a loop, depending on the requirements of the program. A nested while loop in C++ works similarly to the nested loops. The outer while loop is incremented after the termination of the inner while loop.

Syntax

while(condition) {

   while(condition) {     

      // inner loop statement

   }

   // outer loop statement

}

Generally, the inner loop runs for every iteration of the outer loop, up to the termination point. For example, in the example given below, “j” will run up to 5 for every “i” and thus have a time complexity O(n²).

int i = 0;

while(i<=5)

{

     int j = 0;

     while(j<=5)

     {

          //inner loop statement of O(1) complexity

          j++;

     }

     i++;

}

Below is the example of insertion sort displaying the implementation of nested while loops in C++:

#include <bits/stdc++.h>

using namespace std; 

// Function to sort an array using insertion sort

void insertionSort(int arr[], int n)

{

     int i = 1;

     int currElement, j; 

     //using nested while loop

     while(i < n)

     {

          currElement = arr[i];

          j = i - 1; 

          // shift the array elements greater than currElement

          // to an index ahead  

          while (j >= 0 && arr[j] > currElement)

          {

               arr[j + 1] = arr[j];

               j = j - 1;

          }

          arr[j + 1] = currElement;

          i++;

     }

// print the array of size n

void print(int arr[], int n)

{

     for (int i = 0; i < n; i++)

          cout << arr[i] << " ";

     cout << endl;

// Driver code 

int main()

{

     int arr[] = { 5, 4, 3, 2, 1 };

     int n = sizeof(arr) / sizeof(arr[0]); 

     cout<<"Array elements before sorting: ";

     print(arr, n);

      insertionSort(arr, n);

     cout<<"Array elements after sorting: ";

     print(arr, n);

     return 0;

}

While_Loop_In_C_Plus_Plus_3

In the above program, there are two while loops. You nested the inner while loop inside the outer while loop. The outer while loop (i-loop) runs n-times. And for every “i”, the inner loop (j-loop) runs up to n-times in the worst case.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Infinite while Loop in C++

An infinite loop in C++ is one in which the test condition always returns true. If the boolean test condition in a while loop always returns true, then the while loop executes infinite times in such a case. This infinite loop keeps running until the memory overflows.

The following examples show the situations when the test condition will always return true:

while(true) 

{

    // while loop body

}

while(i > 0) 

{   

    // update expression

    i = 1; // i is reassigned to 1 in every iteration

}

The following example illustrates infinite while loop in C++:

#include <iostream>

using namespace std;

int main()

{

    // initialize loop variable

   int i = 4; 

   while(i <= 5) {

      cout << "I am infinite while loop" << "\n"; 

      // update loop variable

      i--;

   }

   return 0;

}

While_Loop_In_C_Plus_Plus_4

In the above program, the loop variable “i” is initialized to 4. The test condition checks if the value of “i” is less than 5 or not. This condition will always return true since “i” is getting decremented inside the while loop. So, after every iteration, the value of the variable “i” will become 4, 3, 2, 1, 0, -1, -2, and so on. This will make the while loop run infinitely or endlessly.

Examples

The following programs illustrate the while loop in C++:

Example1: Program to Reverse the Digits of a Given Number

#include <bits/stdc++.h>

using namespace std;

//function to reverse the digits

int reverse(int n)

{

     int rev = 0;

     while (n > 0) {

          rev = rev * 10 + n % 10; 

     //update expression

          n = n / 10;

     }

     return rev;

}

 //Driver program

int main()

{

     int n = 12345;

     cout << "Reverse of the number is " << reverse(n);

     return 0;

}

While_Loop_In_C_Plus_Plus_5 

In the above program, you find the reverse of the given integer. The while loop is used here to repeat the task of finding the last digit of the number one by one and updating it until the number becomes 0.

Example 2: Program to Check if the Given Number Is Palindrome or Not

#include<iostream>

using namespace std;

//function to check if the number is palindrome

void palindrome(int n) {

   int rev=0;

   int temp = n;

   while(n > 0) {

      rev = rev * 10 + n % 10; 

      //update expression

      n = n / 10;

   }

   if(temp == rev)

   {

       cout<<temp<<" is a palindrome"<<endl;

   }   

   else

   {

       cout<<temp<<" is not a palindrome"<<endl;

   }  

}

//Driver program

int main() {

   palindrome(121);

   palindrome(123);

   return 0;

}

While_Loop_In_C_Plus_Plus_6. 

In the program depicted above, you check if a number is palindrome or not. To check this, a while loop is used. The while loop iterates while the number is greater than 0, and once the number becomes 0, the loop terminates.

Example 3: Program to Print First n Fibonacci Numbers

#include <bits/stdc++.h>

using namespace std;

//function to print first n Fibonacci numbers

void fibonacci(int n)

{

    int first = 0, second = 1;

    if (n < 1)

        return;

    cout << first << " ";

    int i = 1;

    while (i < n) 

    {

        cout << second << " ";

        int third = first + second;

        first = second;

        second = third; 

        //update expression

        i++;

    }

// Driver Code

int main()

{

    int n = 6;

    cout<<"The first "<<n<<" fibonacci numbers are ";

    fibonacci(n);

    return 0;

}

While_Loop_In_C_Plus_Plus%20_7.

The program mentioned above prints the n terms of the Fibonacci series. The task of calculating a term by adding the previous two terms and printing it is done using a while loop. Before the execution of the loop,  the test condition (i < n)  is checked. If n is less than “i”, the loop will not execute. Since this condition is checked at the entry-level, it becomes useful when n is 0 or less than 0, as no term will be printed in that case.

Example 4: Program to Count the Total Number of Digits of a Number

#include <bits/stdc++.h>

using namespace std;

//function to count the number of digits

int digits(int num)

{

    int count = 0;

    while (num != 0)

    {

        num = num / 10; 

        //update expression

        ++count;

    }

    return count;

// Driver code

int main()

{

    int num = 12345678;

    cout << "Total number of digits are : " << digits(num);

    return 0;

}

While_Loop_In_C_Plus_Plus%20_8.

In the above program, you find the total number of digits in a given number. This can be done by simply retrieving the last digit of the number and incrementing the counter. The while loop is used here to execute this task until the number n becomes 0.

Difference Between for Loop and while Loop

The for loop and the while loop are the most common loops in many programming languages. Now, you will understand how the two differ from each other.

for Loop

The for loop is considered to be the most basic type of loop provided by C++. While dealing with a for loop, you know the number of executions already. This loop includes initialization, testing condition, and increment/decrement in a single line, thus it provides a concise way of applying a loop.

Syntax

for (initialization; testing condition; increment/decrement)

{

    //loop statement

}

Depicted below is a simple code explaining the implementation of the for loop:

#include<iostream>

using namespace std;

int main()

{

     //print 5 multiples of 2

     for(int i = 1; i<=5; i++)

     {

          cout<<2*i<<endl;

     } 

     return 0;

}

While_Loop_In_C_Plus_Plus%20_9

while Loop

The while loop is used when you do not know the number of iterations beforehand. The working of this loop depends on a boolean condition. When this boolean condition gets violated, the loop terminates.

Syntax

initialisation condition

while (boolean condition)

{

   //loop statements

   increment/decrement

}

Below is a simple code explaining the implementation of the while loop:

#include<iostream>

using namespace std;

int main()

{

     //print 5 multiples of 2

     int i = 1;

     while(i<=5)

     {

          cout<<2*i<<endl;

    // update expression

          i++;

     }

     return 0;

}

While_Loop_In_C_Plus_Plus%20_10 

The key differences between the for loop and the while loop are as follows:

FOR LOOP

WHILE LOOP

The for loop is used when the number of iterations is known.

The while loop is used when the number of iterations is unknown.

Variables can be initialized either inside or outside the loop.

Variable initialization must strictly take place outside the loop.

Incrementation/Decrementation can only be done after the execution of the loop statement.

Incrementation/Decrementation can be done before as well as after the execution of the loop statement.

If the condition statement is not being put in the for loop, it would lead to the infinite loop.

If the condition statement is not being put in the while loop, it would lead to the compilation error.

The conditional statement is a relative expression.

The conditional statement can be a relative expression as well as a non-zero value.

There can be some counter variable for the for loop that is declared within the loop declaration.

The while loop does not have any built-in loop control variable.


Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Conclusion

In this article, you learned an important concept that is widely used in almost all programming languages called while loops. Starting with an introduction of loops, you learned the ins and outs of while loops along with the syntax, parts, need, and working of the while loops. Moving ahead, you saw how while loops are different from do-while and for loops with examples of each of them. Next, you learned a few basic programs that can be implemented using while loops. 

You should check out our complete tutorial on C++ Programming for Beginners. This will help you to get a strong grasp of the fundamental concepts of C++.

Don’t just stop here. If you want to give yourself a chance to compete with top developers and land yourself a job in professional software development, check out our complete Full Stack Web Development course taught by top instructors in Simplilearn. You will be able to understand some of the core concepts that are generally used in software development practices. These are DevOps, Agility, Java, CSS, HTML, AWS, etc.

If you want free and unlimited access to top-notch technical online courses, we recommend you try some courses from the free online courses list.

If you have any queries or suggestions for us, please mention them in the comment box and our experts answer them for you as soon as possible.

Happy Learning!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 30 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449