Search

Meta

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 and 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 iii == 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, 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 that continuously prints "10 9 8 7 6 5 4 3 2 1 blastoff! 10 9 8 7 6 5 4 3 2 1 blastoff! ..." Why? Because count >= 0 will never be false! When count is 0, 0 >= 0 is true. Then count-- is executed, and count overflows back to some large number. An since some large number 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. 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 following immediately following the declaration of outer?

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.

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

Quiz Answers

1) Show Solution

2) Show Solution

3) Show Solution

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

32 comments to 5.5 — While statements

  • Cameron

    Why does the last program print

    Instead of

    ? Am I missing something? It seems to only print one number each time it repeats by looking at the code.

    • This happens because there is a loop inside of a loop.

      The outer loop iterates iii from 1 to 5. The inner loop iterates jjj from 1 to iii.

      Each time the outer loop iterates, all of the inner loop iterations are restarted.

      So the first time, iii = 1 and jjj = 1. The inner loop executes once and prints 1.
      The second iteration, iii = 2 and jjj = 1. The inner loop executes twice and prints 1 2.
      The third iteration, iii=3 and jjj = 1. The inner loop executes three times and prints 1 2 3.
      And so on.

    • Noha

      notice what i changed in the given example…

    • Canute

  • Mohamad

    I rerote the code from the first example to request an integer from the user and then add each number to the next number on the row and give the combined sum of the row.

    The resulting output for 5 iterations is:
    Enter the number you want to add up to: 5
    1 = 1
    1 + 2 = 3
    1 + 2 + 3 = 6
    1 + 2 + 3 + 4 = 10
    1 + 2 + 3 + 4 + 5 = 15

    Not sure but If I’m right, but I think this is a fibonacci sequence. (please correct me if I’m wrong)
    It took a while to figure out the logic (and I sure this is probably not the most efficient solution, but it works)… sorry for the lack of comments… I’m gonna go back and comment more. Great Tutorial… I finally feel like I’m getting somewhere.

  • CSESTUDENT

    Is it acceptable to write the quiz question in this way?

    • Quinn

      It’s acceptable and will compile, but for readability it’s a bit ambiguous. It may not be plainly obvious what is meant by 97 and 122.

      I also believe static_cast<char>(chValue) is unnecessary, it should just be chValue.

  • Matthew

    Instead of doing:

    I did:

    It compiled and worked fine. It seems easier than the static_cast code. Is that bad coding/is there a reason why it shouldn’t be done like that?

    Thanks

    • Quinn

      (int)chValue is a C-style cast, whereas static_cast<int>(chvalue) is a C++ style one, and they are different in the fact that C-style casts are less type safe than C++ ones. Because of this, it is always suggested that you do, and get into the habit of doing, static_cast instead of C-style casts. Alex talked about this in lesson 4.4.

  • Radek

    Don’t forget that infinite loops like

    is usually used in web servers!

  • mks

    first i want to thank for this awesome tutorial
    i tried this code

    i thought the output is 1
    12
    123
    but it shows
    1
    12
    wats the wrong can somebody explain

    • nishido

      You would need


      while(jjj<=iii)...

      notice the extra equals. Just using less than stops before the value of iii. So in your code you have, while jjj is between 1 and 2 inclusive (i.e. less than iii which equals a max of 3), print jjj.

  • nishido

    So I tried to solve Euler’s problem #1 (calculate the sum of all multiples of 3 or 5 below 1000) using a while statement, but for some reason there’s a problem with a local variable. Here’s my code:


    int sumOfMultiples(int limit)
    {
    int sum;
    int iii=0;
    while (iii<=limit)
    {
    if (iii % 3 == 0 || iii % 5 == 0)
    {
    sum += iii;
    }
    iii++;
    }

    return sum;
    }

    I keep getting an error when I try to run, saying sum isn’t initialized. When it is. It’s initialized outside the if and while blocks, so it should still carry into those blocks shouldn’t it? If I declare sum as “static int sum” then it works, but I don’t see why it doesn’t work otherwise.

  • pranesh

    the following code prints like:
    98 a
    99 b
    .
    .
    .
    .
    123 z
    what is the problem with the code, please answer?

    int main()
    {

    int iii = 97;
    while (iii <= 122)
    {
    cout << iii << "t" << (char)iii++ << endl;

    }

    return 0;

    }

  • Leolas

    Hi! this is how i made the question 2, i think that is very similar, but i used the correspondent ASCII code instead of the letter; however, it prints the same thing.

  • Jackson maduranga_SAC

  • Francis

    On the last program, What if I wanted to print in reverse to the left like this here:

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

    How should I do it? reply asap.

    • Alex

      My advice would be to figure out how to do 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

      Then replace ‘X’ with ‘ ‘.

  • Andy356

    Hi, I was making a program to check if a number is a palindrome. While doing that, I thought, if I can reconstruct the reverse of a number using single digits, then I can easily reconstruct the number itself. Turns out, not so easy. I’ve dry run this code on paper several times. I keep getting wrong answers. For single digits, I get (10,20,30…) for (1,2,3…). For double digits, for example 15, I get [(1+5)10]+1=61. My mistake constantly slips through my eyes. Please help me out. Here’s the code:

    • Andy356

      Oops. Sorry. I forgot that ^ isn’t the exponent operator and I had to use pow(10,i) from <cmath>. ^_^ Stupid thing lost me marks in school too.

      And I just learned that it is actually a bitwise operator. Now I definitely won’t forget it. :)

      Thank you for your awesome tutorials! I hope you’ll keep updating them as the language evolves.

  • Eric

    Hey!  Just wondering why you are using iii++ instead of ++iii, as you said the latter was preferable in an earlier lesson?

  • ProCodes

    This was mine. Instead of letters, I used starting from a to go to 122 for the end of the characters in the order of the integer char uses. I think this is more performance efficient since static casting and such should only be done is absolutely neccessary.

  • Aacon

    good tutorial.

  • Todd

    Typos.

    "The code block will repeatedly execute until iii == 10" (what do you mean by ‘iii’? This notation hasn’t been introduced yet)

    "Then count-- (--cout) is executed"

    "An (And) since some large number is >= 0"

    "instead of following immediately following the declaration of outer?" (remove the first ‘following’)

    Quiz 3:

    Your solution to Quiz 3 doesn’t appear as code formatting. This is because you start your code with [/code] instead of [code].

    Also, you forgot to write ‘<iostream>’ after ‘#include’.

Leave a Comment

  

  

  

fifteen + three =

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