Language Selector

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)

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 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.


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 2
1 2 3
1 2 3 4
1 2 3 4 5


1) In the above program, why is variable inner declared inside the while block instead of 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

Quiz Answers

1) Show Solution

2) Show Solution

3) Show Solution

5.6 -- Do while statements
5.4 -- Goto statements

57 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…

      • how do i get the previous code to read this?

        pliz reply asap!!!

        • Elpidius

          This program prints:

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

          I hope this helps.

    • 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.


    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?


    • 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
    but it shows
    wats the wrong can somebody explain

    • nishido

      You would need


      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;

    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:

               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 ‘ ‘.

      • UsoToChinmoku

        Well, I created a third loop that prints white space and tied the counter to the outer loop. Is there a better solution?
        (EDIT: I double-posted by mistake, and for some reason can’t edit/delete the older post. Feel free to remove it.)

        • Alex

          The only thing that I can think of is since your inner loop always needs to execute 5 times (to print either a space or a number) perhaps both of the inner loops could be consolidated into a single inner loop that uses an if statement to determine whether it should print a space or a number. The code might be easier to follow since it has one less loop.

  • 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


    "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’.

  • Samirax

    Your solution in Question 2 lacks "return 0;" I think, doesn’t it?

  • Jahan

    I don’t think you’re blastoff code will actually return "10 9 8 7 6 5 4 3 2 1 blastoff! 10 9 8 7 6 5 4 3 2 1 blastoff! …". Once it overflows, count is much much bigger than ten. It returns more like

    "10 9 8 7 6 5 4 3 2 1 blastoff! 4294967295 4294967294 4294967293 4294967292 4294967291 4294967290 4294967289 4294967288 4294967287 4294967286 4294967285 4294967284 4294967283 4294967282 4294967281 4294967280 4294967279 4294967278 4294967277 4294967276 4294967275 4294967274 4294967273 4294967272 4294967271 4294967270 4294967269 4294967268 4294967267 4294967266 4294967265 4294967264 4294967263 4294967262 4294967261 4294967260 4294967259 4294967258 … "

  • Hey Alex. I have cleeared while loop in this tutorial. Can I solve Project Euler questions now or it would take some more time to knock there. What would you expect from me If my knowledge is limited to while loops.

    • Alex

      I’m not familiar with Project Euler. Regardless, my advice is the same: Try it, and if you hit a blocker, come back and learn some more, then try again.

  • "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."

    did you forgot the goto statement here or just left itintentionally. If excluding goto is intentional, please explain why?

  • Jinno

    1.Write a program that will compute for and display the sum of all numbers divisible by 3 from 1 to 1000.

    2.Write a program that will display the following pattern, given the value of n.
    Enter a Number: 5

    3.Write a program that will display the following pattern, given the value of n.
    Enter a Number: 5

    4.Write a program that will display the following pattern, given the value of n.
    Example: if n = 4, output

    5.Write a program that will display the following pattern, given the value of n.
    Example: if n = 5, output
    * *
    * * *
    * * * *
    * * * * *

    Can you help me?

  • Mr D

    In the code snippet below (your last prog from the tutorial) i don’t understands why the program doesn’t print (as first number) "2"!
    Because the first print-out is generated by the code:
    std::cout << inner++ << " ";
    But as inner = 1, surely inner++ evaluates to "2". So it should print "2", right?!

  • Mr D

    Ahhh wait, the compiler first prints inner, then ++’s it????

    So this:
    std::cout << inner++ << " " << inner << "n";
    prints out: 1 2

    I don’t understand that. Or is it a simple question of the arrow of time (compiler-wise) first reading to the end of the word "inner", printing it out, and only then seeing the "++"?


  • > Rule: Always use signed integers for your loop variables.

    I am not OK with this affirmation. Your code is just badly conceived: a count cannot go under 0, so using unsigned integers is the right thing to do, but the code should be organized as follows.

    • Alex

      Bjarne Stroustrup (the creator of C++) says, “The unsigned integer types are ideal for uses that treat storage as a bit array. Using an unsigned instead of an int to gain one more bit to represent positive integers is almost never a good idea. Attempts to ensure that some values are positive by declaring variables unsigned will typically be defeated by the implicit conversion rules.”

      I agree that while you could rewrite the program as you suggest (I need to find a better example), use of unsigned int here is still not recommended.

  • Sreedev

    An easier way to do quiz #2 for beginners who doesn’t know about static_cast is as following:

  • ibran

    how to code that one

  • ibran

    how to code that one using while

  • Rob G.

    Hi Alex, another great session. I used the static cast but an alternative is to use the increment itself that matches the ASCII code (60-95) counter (60-95). Post both

    no static cast:

    former - with static cast

    • Alex

      What you’ve done here is used an C++’s ability to implicitly convert an int to a char. Your compiler should give you warning about this since loss of data may result (since you’re putting the value of a variable with a larger range into a variable with a smaller range).

      Personally, I think the static_cast version is better, as it avoids the temporary variable, and makes it clear you’re intending to do a conversion rather than relying on C++ to infer that.

Leave a Comment




4 × three =

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