C++ While Loop

Featured image depicting C++ while loop

Purpose of while loop in C++

Using loops is a way to execute a part of code a specified number of times.

Earlier we learned, the C++ for loop is used if you know how many times to execute a block of code.

The While loop is used to execute a block of code until a specified condition is true. Alternatively, you can say, if the execution of the specified code repeatedly is not fixed then we use a while loop.

Structure of C++ while loop

This is the general structure of the while loop:

while (condition) {

// statements/code to be executed

// increment/decrement comes here

}

A simple example of using while loop in C++

In the following example, we will simply display numbers from 1 to 10 on screen. For that,

  • We declared an int type variable x and assigned it an initial value of 1.
  • In the while condition we set: x<=10 i.e. Keep on executing the while loop until the value of x is less than or equal to 10.
  • Inside the curly brackets, we displayed the current value of x
  • This is followed by incrementing the value of x by 1. So, in each iteration, the value is incremented by 1.

The code:

#include <iostream>

using namespace std;

int main() {

    int x = 1;

    while (x <= 10) {

        cout <<"Current value of x = " << x << "\n";

        x++;
    }

    return 0;
}

Output:

Current value of x = 1
Current value of x = 2
Current value of x = 3
Current value of x = 4
Current value of x = 5
Current value of x = 6
Current value of x = 7
Current value of x = 8
Current value of x = 9
Current value of x = 10

A program using a while loop with a decrement operator

In this program, we will display the numbers from 10 to 1. Have a look at the code and I will explain it later:

#include <iostream>

using namespace std;

int main() {

    int x = 10;

    while (x >= 1) {

        cout <<"Current value of x = " << x << "\n";
        x--;
    }

    return 0;

}

Output:

CPP-while-decrement

In the above program:

  • We initialized the variable x = 10
  • The condition is to keep on executing the while loop until the value of the x is greater than or equal to 1.
  • In each iteration, we displayed the current value of x.
  • Finally, we decremented the value of x by 1 (x–) in each iteration.

Display odd numbers between 1 to 20 by using C++ while loop

This example displays the odd number between 1 to 20 numbers.

First code and output:

#include <iostream>

using namespace std;

int main() {

    int x = 1;

    while (x <= 20) {

        cout <<"x = " << x << "\n";
        x=x+2;
    }

    return 0;
}

Output:

CPP-while-odd-numbers

In the program:

  • We initialized variable x= 1
  • Set the condition to execute the while till x reaches 20
  • In each iteration, we increment the value of x by 2 i.e. x = x + 2;

Using break statement in while loop example

The C++ break statement is used to terminate loops or switch statements and jump the execution out to the next line of code.

This is generally required when a certain task is achieved while using a while loop.

To demonstrate that, the program below exits the while loop as the value of variable x is equal to 7.

#include <iostream>

using namespace std;

int main() {

    int x = 1;

    while (x <= 10) {

        cout <<"x = " << x << "\n";

        x=x+1;
        if (x == 7) {
          break;
    }
   }

    return 0;

}

output:

x = 1
x = 2
x = 3
x = 4
x = 5
x = 6

You saw this is just like the first example. Except we used an if condition where we checked the value of x.

As it is equal to 7, the break statement is executed, and while loop is exited. So, 7,8,9, and 10 did not display.

Learn more about break statement

An example of using a continue statement with while loop

By using a continue statement, rather than exiting the while loop entirely by using a break statement, you may only omit one or more iterations while keep on iterating the loop until the given condition in the while loop is true.

In the following example, we will display numbers from 1 to 10 while omitting the numbers 3 and 7. Have a look:

#include <iostream>

using namespace std;

int main() {

    int x = 1;

    while (x <= 10) {

     if (x == 3 || x == 7){

        x=x+1;
        continue;
    }
        cout <<"x = " << x << "\n";
        x=x+1;
    }

    return 0;

}

Output:

x = 1
x = 2
x = 4
x = 5
x = 6
x = 8
x = 9
x = 10

You can see, the if condition is used to check the value of x. We used or operator (||) in the condition to check value = 3 and 7.

As the condition is true, the continue statement executed that omitted the current iteration of the while loop, and the value of x did not display for numbers 3 and 7.

An example of using a nested while loop

You may write a while inside another while loop.

  • This is called a nested while loop.
  • For each iteration of the outer while loop, the inner while loop executes completely.

See an example of its usage below:

#include <iostream>

using namespace std;

int main () {

        int x=1;

        //Outer while loop

          while(x<=4)

          {

              int y = 1;

              //Inner while loop

              while (y <= 4)

{

            //Display current values of x and y

            cout<<x<<" "<<y<<"\n";

            y++;

          }

           x++;

        }

    }

CPP-while-nested

An example of displaying the table of 15 by using while loop

The following program of C++ displays the table of 15 by using a while loop. Have a look at the code and output:

#include <iostream>

using namespace std;

int main() {

    int x = 1;

    int y = 15;

    while (y <= 150) {

        cout <<"15 * "<<x <<"   = " << y << "\n";

        x++;

        y=y+15;

    }

    return 0;

}

Output:

15 * 1 = 15
15 * 2 = 30
15 * 3 = 45
15 * 4 = 60
15 * 5 = 75
15 * 6 = 90
15 * 7 = 105
15 * 8 = 120
15 * 9 = 135
15 * 10 = 150

 

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!