Programming Languages - school of programming - while C++ - while loop c++

While Loop C++: What You Need to Know

Using loops to simplify code is part of every programmer’s toolkit. Without loops, imagine having to type out the same chunk of code over and over, just to achieve an incremental output. Think about how long it would take for that code to compile. 

Fortunately, C++ loops like the while loop exist to avoid all that hassle.

What Is the While Loop in C++?

C++ developers use loops to repeat a block of code without having to repeatedly type it out. Loops help keep code more concise and make it more readable.

The while loop C++ is a type of loop that will first evaluate a condition. If the condition is true, the program will run the code inside of the while loop. It will then go back and re-evaluate the condition. Every time the condition is true, the program will perform the code inside the loop. Only once the condition is false will the code inside the brackets no longer be executed.

while (condition) {
  // code to be performed when the condition is true
}

It’s worth noting that C++ while loops are similar to do-while loops, but with one significant difference. In do-while loops, the code inside the loop is performed before the condition is evaluated for the first time. Unlike in the C++ while loop, even if a condition is false when the do-while loop is first run, the program will still run through the loop once.

C++ While Loop in Practice

You’ll frequently see the while loop in C++ used as an incremental counter to output values that meet the condition of the loop. Here’s an example:

int main()
{
  int x = 0;
  while (x <= 10) {
    cout << x << " ";
    x+=2;
  }
   
    return 0;
}

This while loop starts with variable “x” at 0. Remember that the while loop will check the condition before performing the code inside the loop. It will generate outputs as long as “x” is less than or equal to 10. Since “x” starts at 0 and meets our condition, the first output will be 0. The loop will terminate once “x” gets above 10. Here’s the result:

0 2 4 6 8 10

There are times where you need to break out of a C++ while loop. Here’s an example of how that works:

int main()
{
  int z = 0;
  while  (z <= 20) {
    if (z == 7) {
      break;
    }
    cout << z << "\n";
    z++;
  }  
  return 0;
}

This while loop would normally increment by 1 until “z” reaches 21, upon which the loop would terminate. However, since we’ve added a break for once “z” hits 7, the break throws us out of the loop before it has a chance to finish counting to 20. In this program, the code terminates at that point.

When Are While Loops Useful?

As we mentioned earlier, while loops are beneficial for repeat operations that require a condition for when the loop should be active. If you want an incremental counter or to display a line of text one thousand times, it’s best to use a while loop. With just a few lines of code, there’s no limit to how high you can increment a number.

Another practical use of the while loop involves iteration through an array or a vector. You can use the while loop to move through a vector or array and output data from said source until the end of the vector or array is reached.

Since the C++ while loop requires a condition, you can use an integer to track your current position in the vector versus the vector’s total size. Once you’ve reached the end of the vector, the while loop will terminate.

It’s also possible to use while loops while reading from standard input. If you have a chunk of text in your code and want to output it, you can use a while loop to go through your input line by line until the loop reaches the end of the text. Using while “input is not false” as the condition will terminate the loop once there’s no more input.

Alternatives to While Loops

While loops can get you in trouble if you’re unsure how many times you need the loop to run. Since the code requires a specific condition to fail to terminate, it’s essential to create a condition that causes the loop to run precisely the number of times you need it to. Otherwise, you may end up with incorrect outputs, not enough outputs, or worst of all: the infinite loop.

There are some notable alternatives to while loops, but some alternatives can work better than others in specific situations.

If Statement

When working with a simple while loop, you could instead use the classic if statement. By embedding if statements into each other, you can increment a counter as we did in our first example above. Here’s the start of the code:

int main()
{
    int x = 0;
    if (x < 6) {
      cout << x << " ";
      x++;
      if (x < 6) {
        cout << x << " ";
        x++;
      }
    }
    return 0;
}

This code checks to see if “x” is less than 6, and in the affirmative it returns the current value of “x” before incrementing it by one. When we eventually reach the end of this series of if statements, we’ll need to use an else statement to close everything out. It does the job but is definitely not recommended under normal circumstances. It’s longer and not nearly as readable. With an if statement, you’ll never get stuck in an endless loop, though.

Switch Statement

A switch statement allows you to list out a series of cases. Much like an if statement, each case will generate an output if that particular case is met. Once again, you need not worry about getting stuck in an infinite loop, but you’re left listing out all the possible cases you’ll need to replace the while loop.

Do-While Loop

As we discussed earlier, a do-while loop is similar to a while loop with one exception. The do-while loop always runs once before the condition is ever checked, per the following example:

int main()
{
    int x = 6;
do {
    cout << x << "\n";
    x++;
} while (x < 5);
    return 0;
}

This code outputs 6, the initial value of “x,” and then checks the condition. Since the condition fails, 6 becomes our only output!

In some cases, it’s possible to write code without the use of loops or other flow controls. However, a developer should always consider how that decision would impact the code’s readability and functionality.

For Loops As While Loops

Another alternative to writing a while loop is the for loop. In fact, it’s entirely possible to rewrite any while loop as a for loop. While the implementation code is slightly different, the outcome if we were to use a while loop would be the same:

int main()
{
    int x = 0;

    while (x <= 10) {
        cout << x <<endl;
        x+=2;
    }
   
    return 0;
}

A for loop requires you to put the initial value of “x,” the condition and what the loop will do if the condition is met — all while declaring the loop. Using this method would generate us the same output as above:

int main()
{
  for(int x=0; x<=10; x+=2){
      cout<< x <<endl;
  }
  return 0;
}

As we can see from our for loop example, we initialize “x” to be 0, and as long as “x” is less than or equal to 10, we output the current value of “x” and then add 2 to it. In either case, we get the following result:

0
2
4
6
8
10

Become a C++ Developer

Loops — including the while loop — are one of the many elements you’ll need to learn on your way to becoming a C++ developer. 

Ready to take your knowledge of C++ to the next level?

Our expert-taught C++ Nanodegree not only covers everything you need to know about loops, but also gives you the opportunity to build your own C++ application. Enroll today! 

Start Learning