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, in the following example, we'll omit the init-statement and end-expression:

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)

This might be a little unexpected, as you'd probably expect an omitted condition-expression to be treated as "false". However, the C++ standard explicitly (and inconsistently) defines that and omitted condition-expression in a for loop should be treated as "true".

We recommend avoiding this form of the for loop altogether and using while(true) instead.

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 assign (in the init-statement) or change (in the end-statement) the value of multiple variables:

This loop assigns values to two previously declared 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.

Note: More typically, we'd write the above loop as:

In this case, the comma in the init-statement is part of the variable definition syntax, not a use of the comma operator. But the effect is identical.

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.

Nested for loops

Like other types of loops, for loops can be nested inside other loops. In the following example, we're nesting a for loop inside another for loop:

For each iteration of the outer loop, the inner loop runs in its entirety. Consequently, the output is:


Here's some more detail on what's happening here. The outer loop runs first, and char c is initialized to 'a'. Then c <= 'e' is evaluated, which is true, so the loop body executes. Since c is set to 'a', this first prints 'a'. Next the inner loop executes entirely (which prints '0', '1', and '2'). Then a newline is printed. Now the outer loop body is finished, so the outer loop returns to the top, c is incremented to 'b', and the loop condition is re-evaluated. Since the loop condition is still true the next iteration of the outer loop begins. This prints ("b012\n"). And so on.


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

161 comments to 5.7 — For statements

  • Jester

    This is my code for number adder you can input number you want but take not this can only hold small numbers because this is an int.

  • ajax

    how to write this output


  • mohamed

    this programme works ,but when i inter number programme stop working
    but if i change the line


    the programme work and not stop.


    • Alex

      This program is a good candidate for using a debugger.

      The problem is that you have a logic error. This code:

      is inside the for loop instead of outside it.

      You also need to guard against even_counter or odd_counter being 0, so you don't end up with a divide by 0 error.

      • mohamed

        ok,thanks very much. but what is the difference between [even_average=1.0*even_sum/even_counter;] and
        [even_average = even_sum / even_counter;]?i mean what that number (1.0) do so programme work in the first code and not in second ,although we know that {1.0*0/0=undifined}.

        • Alex

          even_sum / even_counter does integer division, since both operands are integers.
          1.0*even_sum/even_counter resolves as (1.0 * even_sum) / even_counter. Since 1.0 is a float, 1.0 * even_sum is a float, and that makes the resulting division a floating point division.

          In the top case, doing an integer division by 0 will result in your program having a divide by 0 error, which will cause your program to terminate.
          In the bottom case, doing a floating point division by 0 will result in "inf" (infinity), and your program will keep running.

  • mohamed

    #include <iostream>
    using namespace std;
    int main() {int n,sum;
        for( n=1;n<=10;n++);


        return 0;

    why when i put semicolon at the end of for loop

    the output is 11?

    what semicolon do? i want illustration of this?

    • Alex

      Is the same as:
      for( n=1;n<=10;n++) ; { sum=sum+n; } [code] In other words, that semicolon after your loop is being treated as a null statement. Your loop is looping 10 times, but each iteration is executing the null statement. Then sum=sum+n executes once after the loop is done.

      • mohamed

        ok, sum=sum+n executes once after the loop is done,but after the loop is done the last value of (n)   n=10 ,

        so sum must be sum=10 and not 11.

        why the output of sum is 11? illustrate me please. thanks.

        • Alex

          Because your loop condition is n<=10. This means that when n is 10, 10<=10 is true, and so your loop executes. Since your loop statement is a null statement, nothing happens, but then n++ is executed and n is incremented to 11. 11<=10 is false, so your loop exits. So sum=sum+n is really sum=0+11 which is 11, not 10. I think you probably meant for your loop condition to be n<10.

  • Rob G.

    Hi Alex. I used modulus operator to tell even/not even.

    • Alex

      This works, but it is quite a bit less efficient. Your for loop is iterating through 20 numbers instead of 10, and is executing an if statement for each one instead of just printing the number.

  • Roee Sefi

    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:

    In this example, the only comma operator is in the "change" part of the loop.
    The initialization is just a comma seperated variable declaration list.
    maybe if iii and jjj were previously declared the example would be more correct

  • int x=5;
    int y=7;
    The Out Put Is
    cout<Prints 5+7=12
    -cout<Prints 5 The Initial Value Of X Because The Increment Operator Is After X.
    -cout<Prints 6....After The Previous Operation Ended The Variable X Incremented By 1...5+1=6
    -cout<Prints 12 Variable Y Is Decremented First Because Decremented Operator Before Y--Became 7-1=6 Adding It To X Which Is 6 Then The Result-----6+6=12
    cout<Prints 6...

  • Mike Brown

    Please Ignore the "string bar = ****. I was practicing this program and testing things out with it; it hasn't done anything to alter the program.

  • Mike Brown

    Hey! My Name is Mike! In my C++ Class We have an assignment with nested for loops where we have to print 4 different triangles. The Output needs to look like this:

    *          **********     **********            *
    **         *********       *********           **
    ***        ********         ********          ***
    ****       *******           *******         ****
    *****      ******             ******        *****
    ******     *****               *****       ******
    *******    ****                 ****      *******
    ********   ***                   ***     ********
    *********  **                     **    *********

    I have gotten it to output the first two triangles, I've got them to appear in a column instead of a row. I've been trying to figure it out for ours, but when I try and change things I either just get an infinite loop which outputs * for an eternity or just blank space. Here is my code: (Please Tell me What I am doing wrong and what I need to fix/ improve, if you can spare the trouble )
    #include <iostream>
    #include <string>
    using namespace std;

    int main()

         int numberUno = 1;
        string bar ="*************";

        for ( int i = 0; i < 10; i++ )//Control loop for rows
            for ( int j = 0; j < numberUno; j++ )//Control loop for the columns
                cout << "*";
            cout << endl;

        for (int i = 0; i < 9; i++ )
            for ( int j = 0; j >  numberUno; j++ )
                cout << "*";
            cout << endl;

        for ( int i = 0; i < 10; i++ )
            for ( int j = 0; j < numberUno; j++ )
                cout <<"*";
            cout << endl;

        for (int i = 0; i < 9;i++ )
            for ( int j = 0; j > numberUno; j++ )
                cout <<"*";
            cout << endl;

        for ( int i = 0; i < 10; i++ )
            for ( int j = 0; j < numberUno; j++ )
                cout <<"*";
            cout << endl;

        for ( int i = 0; i < 9; i++ )
            for ( int j = 0; j > numberUno; j++ )
                cout <<"*";
            cout << endl;

        for ( int i = 0; i < 10; i++ )
            for ( int j = 0; j > numberUno; j++ )
                cout <<"*";
            cout << endl;

    Thank You So Much!

    • Alex

      I won't fix your code, but I will give some insight into how I'd tackle the problem:
      1) Know your constraints. In this case, once you move the cursor to the next line, you can't get back. That means outputting your triangles vertically and then figuring out how to make them horizontal isn't going to work well. So you need to consider one row at a time.
      2) Consider the pattern of both stars and of spaces.

      My guess is that this will be most easy to implement using 7 inner loops.

    • Jim

      I hate to tell you this but you only have 2 triangles shown here the other two figures have 4 sides so they're not triangles. However you can make the other into triangles by removing some stars. Here is a thought for you make all the hypotenuses face each other.
      Good Luck

      • Darren

        Mike probably unintentionally omitted the last line of output that would contain the single asterisks to complete the bottom vertices of the middle two triangles.

  • vasu

    I don't understand how are we putting function calls inside this loop.
    please explain this.

    using namespace std;
    int fun()
    static int num = 40;
    return num--;
    int main()
    for(fun(); fun(); fun())
    cout<<fun()<<" ";
    return 0;

    the output is 38 35 32 29 26 23 20 17 14 11 8 5 2

    • Alex

      First, don't ever do this. This is one of those ridiculous academic exercises.

      Remember how for loops work:
      The left side is evaluated when the for loop is entered. Normally we use this to initialize our loop variables, but this can be left blank or to do whatever we want.
      The middle part is evaluated -- if it evaluates to true (non-zero) then the loop executes.
      The right part is evaluated after every loop. Normally we use this to change our loop variable, but this can also be left blank or to do whatever we want.

      Based on that, you should be able to decipher why this produces the output it does. It's fairly straightforward when you understand when each of the parts of the for loop is evaluated.

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

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

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

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

  • lalit

    you missed out foreach loop.

    can you Include that as well in the tutorial.

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

  • 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!)"

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

  • 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

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

  • 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! 😛

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

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

  • derelove

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

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

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

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

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

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

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

Leave a Comment

Put all code inside code tags: [code]your code here[/code]