Language Selector

5.7 — For statements

By far, the most utilized looping statement in C++ is the for statement. The for statement (also called a for loop) is ideal when we know exactly how many times we need to iterate, because it lets us easily define, initialize, and change the value of loop variables after each iteration.

The for statement looks pretty simple in abstract:

for (init-statement; condition-expression; end-expression)

The easiest way to understand a for loop is to convert it into an equivalent while loop:

{ // note the block here
    while (condition-expression)
} // variables defined inside the loop go out of scope here

The variables defined inside a for loop have a special kind of scope called loop scope. Variables with loop scope exist only within the loop, and are not accessible outside of it.

Evaluation of for statements

A for statement is evaluated in 3 parts:

1) The init-statement is evaluated. Typically, the init-statement consists of variable definitions and initialization. This statement is only evaluated once, when the loop is first executed.

2) The condition-expression is evaluated. If this evaluates to false, the loop terminates immediately. If this evaluates to true, the statement is executed.

3) After the statement is executed, the end-expression is evaluated. Typically, this expression is used to increment or decrement the variables declared in the init-statement. After the end-expression has been evaluated, the loop returns to step 2.

Let’s take a look at a sample for loop and discuss how it works:

First, we declare a loop variable named count, and assign it the value 0.

Second, count < 10 is evaluated, and since count is 0, 0 < 10 evaluates to true. Consequently, the statement executes, which prints 0.

Third, ++count is evaluated, which increments count to 1. Then the loop goes back to the second step.

Now, 1 < 10 is evaluated to true, so the loop iterates again. The statement prints 1, and count is incremented to 2.
2 < 10 evaluates to true, the statement prints 2, and count is incremented to 3. And so on.

Eventually, count is incremented to 10, 10 < 10 evaluates to false, and the loop exits.

Consequently, this program prints the result:

0 1 2 3 4 5 6 7 8 9

For loops can be hard for new programmers to read -- however, experienced programmers love them because they are a very compact way to do loops of this nature. For the sake of example, let's uncompact the above for loop by converting it into an equivalent while loop:

That doesn't look so bad, does it? Note that the outer braces are necessary here, because count goes out of scope when the loop ends.

More for loop examples

Here's an example of a for loop used to calculate an exponentiation of integers:

This function returns the value base^exponent (base to the exponent power).

This is a straightforward incrementing for loop, with count looping from 0 up to (but excluding) exponent.

If exponent is 0, the for loop will execute 0 times, and the function will return 1.
If exponent is 1, the for loop will execute 1 time, and the function will return 1 * base.
If exponent is 2, the for loop will execute 2 times, and the function will return 1 * base * base.

Although most for loops increment the loop variable by 1, we can decrement it as well:

This prints the result:

9 8 7 6 5 4 3 2 1 0

Alternately, we can change the value of our loop variable by more than 1 with each iteration:

This prints the result:

9 7 5 3 1

Off-by-one errors

One of the biggest problems that new programmers have with for loops (and other kinds of loops) is off-by-one errors. Off-by-one errors occur when the loop iterates one too many or one too few times. This generally happens because the wrong relational operator is used in the conditional-expression (eg. > instead of >=). These errors can be hard to track down because the compiler will not complain about them -- the program will run fine, but it will produce the wrong result.

When writing for loops, remember that the loop will execute as long as the conditional-expression is true. Generally it is a good idea to test your loops using known values to make sure that they work as expected. A good way to do this is to test your loop with known inputs that cause it to iterate 0, 1, and 2 times. If it works for those, it will likely work for any number of iterations.

Rule: Test your loops with known inputs that cause it to iterate 0, 1, and 2 times.

Omitted expressions

It is possible to write for loops that omit any or all of the expressions. For example:

This for loop produces the result:

0 1 2 3 4 5 6 7 8 9

Rather than having the for loop do the initialization and incrementing, we've done it manually. We have done so purely for academic purposes in this example, but there are cases where not declaring a loop variable (because you already have one) or not incrementing it (because you're incrementing it some other way) are desired.

Although you do not see it very often, it is worth noting that the following example produces an infinite loop:

for (;;)

The above example is equivalent to:

while (true)

Multiple declarations

Although for loops typically iterate over only one variable, sometimes for loops need to work with multiple variables. When this happens, the programmer can make use of the comma operator in order to initialize or change the value of multiple variables:

This loop initializes two variables: iii to 0, and jjj to 9. It iterates iii over the range 0 to 9, and each iteration iii is incremented and jjj is decremented.

This program produces the result:

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

This is the only place in C++ where the comma operator typically gets used.

For loops in old code

In older versions of C++, variables defined as part of the init-statement did not get destroyed at the end of the loop. This meant that you could have something like this:

This use has been disallowed, but you may still see it in older code.


For statements are the most commonly used loop in the C++ language. Even though its syntax is typically a bit confusing to new programmers, you will see for loops so often that you will understand them in no time at all!


1) Write a for loop that prints every even number from 0 to 20.

2) Write a function named sumTo() that takes an integer parameter named value, and returns the sum of all the numbers from 1 to value.

For example, sumTo(5) should return 15, which is 1 + 2 + 3 + 4 + 5.

Hint: Use a non-loop variable to accumulate the sum as you iterate from 1 to the input value, much like the pow() example above uses the total variable to accumulate the return value each iteration.

3) What's wrong with the following for loop?

Quiz solutions

1) Show Solution

2) Show Solution

3) Show Solution

5.8 -- Break and continue
5.6 -- Do while statements

40 comments to 5.7 — For statements

  • csvan

    Hi Alex,

    I am nowhere near you as far as experience is concerned, but I wonder why you use a postfix ++ within loop blocks? Isnt this less efficient then using it as a prefix, since the postfix (as far as I know) creates a temporary variable for the purpose of evaluation? Besides, a postfix adds nothing to the functionality here (I think!), if the incrementation is evaluated after the loop condition but before the statements within the loop scope itself (if it works this way).

    Did I miss something?

    • Quinn

      IIRC, there’s no functional difference between iii++ and ++iii in the second expression with for loops, but standard convention has always been iii++. Maybe as some sort of homage to the c++ language. :) If you prefer it the other way, I wouldn’t really see any reason not to do it that way, with the small exception of having more to work with in the second expression, such as having…

      would be different than…

      • Alex

        Prefix is more efficient than postfix, and should be favored. I’ve updated the examples in the lesson to use prefix increments and decrements.

        Personally, I think C++ probably should have been named ++C. :)

  • mike

    Hey Alex,

    Thanks for the great tutorial on C++. I have a question about the example in the multiple declarations section. Why is it not necessary to also put a restriction on jjj (i.e. jjj > 0)?

    • Quinn

      There’s no real need to have a restriction on jjj to have the loop produce the same, controlled sequence. The variable jjj is completely under control within the for loop, so the programmer will generally know what jjj is going to evaluate to by looking at it. It may be necessary that for loops check different conditions, but in that case you shouldn’t really use the comma (,) operator, and instead use logical AND (&&) or logical OR (||).

  • john

    I think question 3 is incorrect. you say

    “This for loop executes as long as nCount >= 0. In other words, it runs until nCount is negative.”

    If that’s the case then your suggesting that 0 is a negative number. It’s not positive or negative.

    You also state back when your introducing unsigned variables:

    Size/Type======== Range
    1 Byte signed===== -128 to 127
    1 Byte unsigned==== 0 to 255

    So i don’t get how the program wouldn’t stop once it hit 0 since it is a unsigned variable?

    • Realth

      0 is technically negative ? I’m not sure.

      “This for loop executes as long as nCount >= 0. In other words, it runs until nCount is negative.”

      Another way of saying this is the loop will stop when nCount < 0.
      However, nCount is unsigned therefore cannot become less than 0. I’m not sure if it can become 0. Regardless, the loop will not stop because nCount cannot ever be less than 0.

      Hope this helps.

  • Pixy

    Hi there,
    Thanks for this tutorial, i missed my last class which was on loops and didn’t know ANYTHING, until your site, I actually did the quiz without cheating and got the right answers. Can you help me with this problem?

    for (int x = 12; x>= 7;)
    printf(“%d\n”, x); …..What gets printed out? Is it 12, because there is no update to be done?


    • alwaysAstudent

      your program will go into infinite loop printing 12. x is 12 and 12 will always be >= 7 so it will keep on printing 12. the program may hang the console screen on some systems.

  • hsh

    hi to all;
    i have a question:
    when we use two for loop without{},how does it work?

    for example:

    for(int i=1;i<=3;i++)

    • smitha

      j runs from 1 to 3 and the outer loop runs 3 times

      • Alex

        The outer loop (controlled by i) runs first, and it will run 3 times.

        For each iteration of the outer loop, the inner loop will run 3 times.

        So it will run in this order:
        i=1 j=1
        i=1 j=2
        i=1 j=3
        i=2 j=1
        i=2 j=2
        i=2 j=3
        i=3 j=1
        i=3 j=2
        i=3 j=3

        You could have determined this yourself by putting a print statement after the second loop and testing it experimentally.

  • dhysk

    Ok, I’m having an issue with this Quiz question #2. Although I changed the requirments so that I could do a sum from one user defined int to another user defined int. I also wanted to practice making using functions.

    In Main.cpp The nReadNumber() was from getting tired of always making user input commands for ints ;). Lazzy I know.

    In file io.cpp

    In file Calculate.cpp

    Ok I was getting out 0 every time; however I found that for some reason nx and ny inputs were getting reversed there for inputing the lower number first then the higher number nx will always be > ny. When I don’t use the nReadNumber function and just input the numbers it works fine.

    By reversed I mean the first number I put in is ny and the second number is nx. Is this normal behaviour for functions to evaluate the inside from right to left?

    • Alex

      It’s undetermined whether functions evaluate left to right or right to left. Congratulations, you’ve found a case where it matters. :)

  • derelove

    i am new to this website ,it is very good,keep it doing. how can i ask questions?

  • Well, I have written another function wich handles negative exponents, e.g. 2^-3

    The only thing I changed about the original function “Exponent” is change the name to “PositiveExponent”.
    Here it is, along with a little bit more code:

    The function self:

    The program (which asks for two integer values from the user, and then does the nBase ^ nExp calculation on them):

    That’s it, just wanted to contribute something back 😉
    Have fun coding!

    • Oops, forgot two small things:

      The beginning of the main function should begin with:

      And the last piece of code should be:

      Just a little mistake which (I hope) your compiler will complain about. Not anymore 😉

  • Moogie

    It was a very small victory for me, but when doing Quiz #2 I came up with a different, but equally decent solution, all by my wittle self. :)

    Felt so pleased with myself after seeing it worked! lol. I’m learning so much from this site, I can’t express my gratitude enough to you, Alex!

  • Shishka

    While looking at quiz #2 I noticed a pattern, and since I was bored I wrote the following.

    Which gives the same answer as your solution, but much more quickly with larger numbers. It seems to be accurate with input up to at least 1,000,000,000.

    I’m a regular mathematician! 😛

  • Iodream

    I’m a full beginner in C++ and got stuck at an exercise which looks pretty simple to my mind at first look,
    i have no idea why it doesn’t work.
    It just outputs the “1”.
    There are no compiler errors, juts a notification that i’m using an obsolete way of using getch().
    Perhaps i’m even completely wrong, i just need some help.

    Task: write all perfect numbers from 1 to 100.


    Thanks in advance for any help.

    • First of all - only thing it should type is 6 and 28, because those are the only perfect numbers below 100, and 1 is not a perfect number.
      Also, I advise you to use debugging breakpoints to follow the process of your program and catch the bug at fault.

  • Elias

    I must say your Tutorials are very well writen, I programmed something which put out all prime numbers and count them (prisZZ.size are all prime numbers counted and prisZZ.number ist the last number if the choosen is not a prime number) i tested it for 10.000.000 - works fine and shows the right numbers 😉

    result for 1000:
    Put in a Number for X:
    All Prime Numbers to 1000 are:
    2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997
    Prime numbers count:168
    Last prime number:997
    1000 is no prime number

  • alan

    But I’m using Visual C++ 2013 for Windows Desktop and doesn’t complain about using my variable after the while loop has finished,
    just outputs 100 as I would expect.

    Or am I missing something?

  • Todd


    "Typically, this expression consists of incremented/decrementing (incrementing/decrementing)"

    "Let’s uncompact the above for loop by converting it into it’s (its) while-statement equivalent:"

    "This loop initializes two variable: (variables:)"

    "Even though it’s (its) syntax is typically a bit confusing"

    "Write a function named SumTo()" ("SumTo()" should be "sumTo()" by naming conventions)

    "For example, SumTo(5)" (should be "sumTo(5)")

    Quiz 2: in the problem statement, you say the function should take in a parameter named nValue, but in your solution you call this parameter nSumTo.

    The function in Quiz 2 solution should be named "sumTo()" and not "SumTo()" by naming conventions

    Quiz 3 solution: "Consequently, this for loop will run for-ever! (forever!)"

  • In quiz #2, question asks to take a parameter named "value" and your solution is taking a parameter named "sumto".
    Great tutorial…Thanks!

  • lalit

    you missed out foreach loop.

    can you Include that as well in the tutorial.

  • Aryan

    Hey Alex!
    I have never really thanked you for what you are doing here, but great job man! You are doing great here

    Just a small confusion (Still don’t know how to use an apple debugger!), in the exponent example you wrote :

        I just want to know when was count identifier ever used outside loop, I mean how did the "total *= base" statement knew that if count is n times the base has to multiply itself by n times?

    Eg : if count = 0, so 0 < exponent(true), but where does count goes after that?

    • Alex

      For statements execute until the conditional is false. In this case, the conditional is “count < exponent”. Count starts at 0, and increments by one each iteration of the loop, until it reaches the value of exponent (at which point the conditional is false and the loop exits). This means the loop will execute the same number of times as the value of variable exponent. Each time it executes, it will run the total *= base line of code. Thus, we execute the “total *= base” line of code a number of time equal to the value in variable exponent. Make sense?

  • Aryan

    Hey Alex!
    What would happen if I nested for loops?
        Like :

    It prints the result : 112233

    So I thought to find out from where to where the evaluation sequence starts and ends, and the results (i think) were stunning, it starts from the inside loop, if the j loop is false it goes straight to "cout<<i;" part! Then it goes straight to i loop (the outside loop) and back to j loop. Its all pretty fascinating.  So I am trying to make nested loop program that would print :
                 A           B
             A        B         C

    And also I tried adding this to the upper program : for (int j = i; j<=++i; ++j) and it printed : 12345….to infinity! My laptop went ballistic and there was a rise of 4% CPU usage!

    • Alex

      I think you were misled by a faulty experiment: the “cout << i” statement should be inside the outer for loop:

      You’ll see that the outside loop executes first. For each iteration of the outside loop, the inside loop executes in its entirety.

  • Mr D

    Hi Alex,

    Sorry to be bugging you like every evening, but….
    ….. i can’t get my head around quiz two.

    The "for" statement ends with "++count".
    So why doesn’t it output "2" first time around? So, 2+3+4+5=14.
    Sorry for being a dumbass!

    • Alex

      Don’t be so hard on yourself.

      The last statement of the for loop only executes AFTER the for loop executes.

      So the first time the for loop runs, count = 1. count <= value is true, so the loop executes. Total += count, so total = 1. Then ++count executes, and count is incremented to 2. Then we start again. cout <= value is true, so the loop executes again. Total += count, so total = 1. Then ++count executes, and count is incremented to 3. Repeat until ++count makes count equal to 6, at which point count <= value is false and the loop terminates. At that point, total has added 1 + 2 + 3 + 4 + 5 = 15.

  • Mr D

    Ok, sorry, after re-reading the tutorial, you explained it, the first time the "for" statement runs in just evaulates to the initialized value(s), only the second time does it look beyond that.

Leave a Comment




20 + 1 =

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