Search

5.5 — While statements

The while statement is the simplest of the four loops that C++ provides, and it has a definition very similar to that of an if statement:

while (expression)
    statement;

A while statement is declared using the while keyword. When a while statement is executed, the expression is evaluated. If the expression evaluates to true (non-zero), the statement executes.

However, unlike an if statement, once the statement has finished executing, control returns to the top of the while statement and the process is repeated.

Let’s take a look at a simple while loop. The following program prints all the numbers from 0 to 9:

This outputs:

0 1 2 3 4 5 6 7 8 9 done!

Let’s take a closer look at what this program is doing. First, count is initialized to 0. 0 < 10 evaluates to true, so the statement block executes. The first statement prints 0, and the second increments count to 1. Control then returns back to the top of the while statement. 1 < 10 evaluates to true, so the code block is executed again. The code block will repeatedly execute until count is 10, at which point 10 < 10 will evaluate to false, and the loop will exit.

It is possible that a while statement executes 0 times. Consider the following program:

The condition 15 < 10 immediately evaluates to false, so the while statement is skipped. The only thing this program prints is done!.

Infinite loops

On the other hand, if the expression always evaluates to true, the while loop will execute forever. This is called an infinite loop. Here is an example of an infinite loop:

Because count is never incremented in this program, count < 10 will always be true. Consequently, the loop will never terminate, and the program will print "0 0 0 0 0 ..." forever.

We can declare an intentional infinite loop like this:

The only way to exit an infinite loop is through a return statement, a break statement, an exit statement, a goto statement, an exception being thrown, or the user killing the program.

Programs that run until the user decides to stop them sometimes intentionally use an infinite loop along with a return, break, or exit statement to terminate the loop. It is common to see this kind of loop in web server applications that run continuously and service web requests.

Loop variables

Often, we want a loop to execute a certain number of times. To do this, it is common to use a loop variable, often called a counter. A loop variable is an integer variable that is declared for the sole purpose of counting how many times a loop has executed. In the examples above, the variable count is a loop variable.

Loop variables are often given simple names, such as i, j, or k. However, naming variables i, j, or k has one major problem. If you want to know where in your program a loop variable is used, and you use the search function on i, j, or k, the search function will return half your program! Many words have an i, j, or k in them. Consequently, a better idea is to use iii, jjj, or kkk as your loop variable names. Because these names are more unique, this makes searching for loop variables much easier, and helps them stand out as loop variables. An even better idea is to use "real" variable names, such as count, or a name that gives more detail about what you're counting.

It is best practice to use signed integers for loop variables. Using unsigned integers can lead to unexpected issues. Consider the following code:

Take a look at the above example and see if you can spot the error. It's not very obvious.

It turns out, this program is an infinite loop. It starts out by printing "10 9 8 7 6 5 4 3 2 1 blastoff!" as desired, but then goes off the rails, and starts counting down from 4294967295. Why? Because the loop condition count >= 0 will never be false! When count is 0, 0 >= 0 is true. Then --count is executed, and count overflows back to 4294967295. And since 4294967295 is >= 0, the program continues. Because count is unsigned, it can never be negative, and because it can never be negative, the loop won't terminate.

Rule: Always use signed integers for your loop variables.

Iteration

Each time a loop executes, it is called an iteration.

Because the loop body is typically a block, and because that block is entered and exited with each iteration, any variables declared inside the loop body are created and then destroyed with each iteration. In the following example, variable x will be created and destroyed 5 times:

For fundamental variables, this is fine. For non-fundamental variables (such as structs and classes) this may cause performance issues. Consequently, you may want to consider defining non-fundamental variables before the loop. This is another one of the cases where you might declare a variable well before its first actual use.

Note that variable count is declared outside the loop. This is necessary because we need the value to persist across iterations (not be destroyed with each iteration).

Often, we want to do something every n iterations, such as print a newline. This can easily be done by using the modulus operator on our counter:

This program produces the result:

01 02 03 04 05 06 07 08 09 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50

Nested loops

It is also possible to nest loops inside of other loops. In the following example, the inner loop and outer loops each have their own counters. However, note that the loop expression for the inner loop makes use of the outer loop's counter as well!

This program prints:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Quiz

1) In the above program, why is variable inner declared inside the while block instead of immediately following the declaration of outer?

Show Solution

2) Write a program that prints out the letters a through z along with their ASCII codes. Hint: to print characters as integers, you have to use a static_cast.

Show Solution

3) Invert the nested loops example so it prints the following:

5 4 3 2 1
4 3 2 1
3 2 1
2 1
1

Show Solution

4) Now make the numbers print like this:

        1
      2 1
    3 2 1
  4 3 2 1
5 4 3 2 1

hint: Figure out how to make it print like this first:

X X X X 1
X X X 2 1
X X 3 2 1
X 4 3 2 1
5 4 3 2 1

Show Solution

5.6 -- Do while statements
Index
5.4 -- Goto statements

161 comments to 5.5 — While statements

  • Norbert

    This prints:
        1
       2 1
      3 2 1
    4 3 2 1
    5 4 3 2 1

    A pyramid! Not even mad!
    I’m still figuring out why though.

    • Bryan

      Hi Norbert,

      I had the exact same problem.
      The issue here is that in the else statement
      the std::cout << " " has only one space, and it should have 2.
      It is easy to overlook errors as these, it took me a while to find it.

      When using the breakpoint debugger and going step-by-step through the
      code I noticed this and I saw why this made sense.

      Also Alex has also stated it in his comment inside the answer.

  • Hema

    My teacher told that we are not supposed to create variables at the run-time. Why is that so?

    • Alex

      By “at the run-time”, it sounds like your teacher is talking about the difference between dynamically allocated and non-dynamically allocated variables.

      While you should certainly prefer non-dynamically allocated variables all else being equal, there are many times when dynamic allocation is required.

      Assuming you understood correctly, what was your teacher’s reason for such a statement?

  • Hema

    I am writing a code in which the following has to be done- creating the number of varibles that the user wants. Here is the code

    How can I use the variables created, outside the loop?

    • Alex

      The best way to do this would be to declare an array of integers outside of the loop, after the user has told you how many variables they want.

      If you’re using a non-dynamic array, create a large array and only use the elements the user wants. If you’re using a dynamic array, you can create exactly the number of elements the user wants.

      Arrays and dynamic allocation are both covered in chapter 6.

  • Hema

    I am creating a variable inside a while loop. What should I do so that I will be able to use it outside the loop too?

  • Kushagra

    Alex please tell me the method how to solve these quiz. because putting values arbitrarily and checking the result,  is a cumbersome  process and time consuming.

    • Alex

      Trial and error. Try something, if it doesn’t work, figure out why and fix it. Odds are your program works correctly up to a point and then goes wrong. Using the debugger can be _very_ helpful to discover where your program is going wrong, which will give you insight into what you need to fix.

  • joery

    small error (I think)
    3) Invert the nested loops example so it prints the following:

    5 4 3 2 1
    4 3 2 1
    3 2 1
    2 1
    1

    the original loop printed:
    1
    12
    123
    1234
    12345

    so answer should be:
    5
    54
    543
    5432
    54321

    It is good practice to do them both ways but yeah… haha

  • Zero Cool

    I really make a mess with Quiz 4 (I’m so tired right now) so I give up and made the following code:

    main.cpp

    The following code is just for fun…

  • Zero Cool

    My solution for Quiz 3:

    main.cpp

  • Zero Cool

    My solution for the Quiz 2:

    io.h

    io.cpp

    main.cpp

  • Luhan

    In the code of soluton 3 would be better if was like this :

    The second loop need to use pre-decrement, otherwise will print like this (5-5-4-3-2-1). The

    could be

    • Alex

      This doesn’t work -- it prints 4 through 0, not 5 through 1.

      • Luhan

        Sorry, probably it was my IDE, I’ve seen some bugs in it, especially when I debug my code.

        • Ross

          If you change the following:

          to this:

          It will fix your problem of only showing 4 to 0, instead of 5 to 1

  • Ryan

    My own solution for #3:

    Same result

  • CrazyL

    My solution for quiz 4 was quite similar to the example solution -- except I used postfix to increase “outer” within the “while” statement in line 9:

  • Stratacos

    When a variable is created and memory space is assigned to it, is that memory space cleared when the variable goes out of scope, or when the console is exited? Or is the space still occupied in the form of a ‘junk file?’

    • Alex

      It depends. For local variables, the memory is freed when the variable goes out of scope. For dynamically allocated variables (which we talk about in chapter 6) they stay in memory until explicitly deleted (or until the program ends).

  • acm1264

    I made my code a little differently with the same result for #3 (I think I made it a bit too complicated but it worked haha!)

  • c++ learner

    can you explain what means inner and outer in quiz samples? I am a little bit confused what that words mean there

  • Said

    Don’t know why but this is the first quiz that I got really frustrated at. I ended up making the 4th quiz more complicated than it needed to be. Gotta practice more I guess.

  • Christoph

    Here is a solution for Quiz number 4 that only uses while statements and is just a slightly modified number 3 code.

  • Caleb

    Hi Alex,

    I am having trouble with a while loop that uses a string instead of an integer as a condition. I believe this should work but, it doesn’t. I have looked into your examples and have learned everything from your fantastic lessons. I could not find a string example. This is a program I created to check my understanding. and I’m open to any criticism.I changed the “False” in line 45 to “false” and it still doesn’t seem to work.

    • Alex

      First thing to check: strings are case sensitive. So right off the bat, your while loop won’t run, because “False” != “false”.

  • James Ray

    My solution for quiz 4:

  • Matheus

    Another solution to the last quiz (4):

    PS: try to change the relational operator in the first if. You get nice results.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter