Navigation



5.7 — For statements

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

The for statement looks pretty simple:

for (init-statement; expr1; expr2)
   statement;

The easiest way to think about for loops is convert them into equivalent while loops. In older versions of C++, the above for loop was exactly equivalent to:

// older compilers
init-statement;
while (expr1)
{
    statement;
    expr2;
}

However, in newer compilers, variables declared during the init-statement are now considered to be scoped inside the while block rather than outside of it. This is known as loop scope. Variables with loop scope exist only within the loop, and are not accessible outside of it. Thus, in newer compilers, the above for loop is effectively equivalent to the following while statement:

// newer compilers
{
    init-statement;
    while (expr1)
    {
        statement;
        expr2;
    }
} // variables declared in init-statement go out of scope here

A for statement is evaluated in 3 parts:

1) Init-statement is evaluated. Typically, the init-statement consists of variable declarations and assignments. This statement is only evaluated once, when the loop is first executed.

2) The expression expr1 is evaluated. If expr1 is false, the loop terminates immediately. If expr1 is true, the statement is executed.

3) After the statement is executed, the expression expr2 is evaluated. Typically, this expression consists of incremented/decrementing the variables declared in init-statement. After expr2 has been evaluated, the loop returns to step 2.

Let’s take a look at an example of a for loop:

for (int iii=0; iii < 10; iii++)
    cout << iii << " ";

What does this do? Although this looks somewhat confusing, let’s take it piece by piece.

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

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

Third, After the statement executes, iii++ is evaluated, which increments iii to 1. Then the loop goes back to the second step.

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

Eventually iii 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. Let's uncompact the above for loop by converting it into it's while-statement equivalent:

{
    int iii = 0;
    while (iii < 10)
    {
        cout << iii << " ";
        iii++;
    }
}

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

Here is an example of a for loop affecting a variable declared outside the for loop:

// returns the value nBase ^ nExp
int Exponent(int nBase, int nExp)
{
    int nValue = 1;
    for (int iii=0; iii < nExp; iii++)
        nValue *= nBase;

    return nValue;
}

This function returns the value nBase^nExp (nBase to the nExp power).

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

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

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

for (int iii = 9; iii >= 0; iii--)
    cout << iii << " ";

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:

for (int iii = 9; iii >= 0; iii -= 2)
    cout << iii << " ";

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 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 expr1 (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 expr1 is true. Generally it is a good idea to test your loops using known values to make sure that they work as expected. If your loop produces the right result when it iterates 0, 1, and 2 times, it will probably work for all number of iterations.

Omitted expressions

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

int iii=0;
for ( ; iii < 10; )
{
    cout << iii << " ";
    iii++;
}

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 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 (;;)
    statement;

The above example is equivalent to:

while (true)
    statement;

Null statements

It is also possible to omit the statement part of a for loop. This is called a null statement, and it is declared by using a single semicolon.

for (int iii=0; iii < 10; iii++)
    ;

This loop increments iii using the ++ operator 10 times. When the statement is executed, the null statement evaluates to nothing, and consequently, doesn't do anything. For readability purposes, the semicolon of a null statement is typically placed on it's own line. This indicates that the use of a null statment was intentional, and makes it harder to overlook the use of the null statement.

Null statements can actually be used anywhere a regular statement can (though they typically aren't, since they serve no purpose other than as a do-nothing placeholder). Because of this, it is easy to make the following mistake:

if (nValue == 0);
    nValue = 1;

The programmer's intent was to assign nValue the value of 1 only if nValue had the value 0. However, due to the misplaced semicolon after the if statement, this actually executes as:

if (nValue == 0)
    ;
nValue = 1;

Consequently, nValue is set to 1 regardless of it's previous value!

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:

    for (int iii=0, jjj=9; iii < 10; iii++, jjj--)
        cout << iii << " " << jjj << endl;

This loop initializes two variable: 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.

Conclusion

For loops are the most commonly used loop in the C++ language. Even though it's 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!

Quiz

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

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

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 nValue, much like the Exponent() example above uses nValue to accumulate the return value each iteration.

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

// Print all numbers from 9 to 0
for (unsigned int nCount = 9; nCount >= 0; nCount--)
    cout << nCount << " ";

Quiz solutions

1) Show Solution

2) Show Solution

3) Show Solution

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

52 comments to 5.7 — For statements

  • Niall the don

    Hello
    I think in your second solution nValue should be nSumTo

    [Yup! Thanks for noticing the mistake. -Alex ]

  • John

    Hi;

    Can you explain quiz example.? I don’t understand the purpose of “nSum += iii;” statement. Particulary nSum +=.
    What it will do exactley.
    Thanks

    int SumTo(int nSumTo)
    {
    int nSum = 0;
    for (int iii=1; iii

  • abhishek raj

    hey !!!!!!!!
    Thanx a lot…
    I read particularly this page and found it too diverse n interesting…
    u people should also try this once.

    keep enjoying,……..

  • [...] 2007 Prev/Next Posts « Six language-independent ways to write better code | Home | 5.7 — For statements » Monday, June 25th, 2007 at 4:54 [...]

  • Daniel
    for (int iii=0; iii < 10; jjj++)
        ;  

    Shouldn’t that be this.

    for (int iii=0; iii < 10; iii++, jjj++)
        ;  

    Great tutorials by the way.

    [ I changed the example slightly because it was incorrect, as you noticed. Thanks! -Alex ]

  • blas januar

    nice one poe. . . sana magbigay kapa ng mas maraming example pra mapadali ung assign q. . hhahaha sayang kasi para d2 nalang aq naghanap. . . but tnx nadin poe.. .

  • [...] 2007 Prev/Next Posts « 5.7 — For statements | Home | 6.1 — Arrays (Part I) » Tuesday, June 26th, 2007 at 4:22 [...]

  • Intelus

    I think you should mention the trouble unsigned ints can cause in loops.
    Examine these two for loops:

    For loop #1:

        for (int iii = 9; iii >= 0; iii--)
        cout << iii << " ";
    

    For loop #2:

        for (unsigned int iii = 9; iii >= 0; iii--)
        cout << iii << " ";
    

    The first one is one of your examples (prints “9 8 7 6 5 4 3 2 1 0″) and uses a signed int.

    The second one, however, uses an unsigned int and produces an infinite loop (Oh noes!). The reason is pretty much obvious – after iii hits 0, decrementing it further results in getting either 65535 (2B int) or 4294967295 (4B int). In other words, iii is always great than or equal to 0.

    By the way, you might want to correct a typo (it’s –> its) in:
    “Let’s uncompact the above for loop by converting it into it’s while-statement equivalent:”

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

      for(int iii = 0; i <= 20; iii = iii++ * 2)

      would be different than…

      for(int iii = 0, i <= 20; iii = ++iii * 2)
  • 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

    // Print all numbers from 9 to 0
    for (unsigned int nCount = 9; nCount >= 0; nCount--)
        cout << nCount << " ";
    

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

  • gagagahahahhaha
    ur such a fucker

  • tnemmoC

    Okay, suppose I have to write a function that does the same as the one in question nº3. Since it’s a triangular number thing, would it be better to just write the expression “x = (x * (x++)) / 2″ instead of a loop?

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

    thanks

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

  • Gangadhar Lahane
         Hey Alex...
         Thanks a lot for your tutorials. I have  problem about the multiple declaration of variables within the for loop...
         Explain it with on simple example plz.
    
  • ryan

    the output is

    *
    * *
    * *
    * * * * *

    what is the input? can you give me….

  • 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++)
    for(j=1;j<=3;j++)

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

    using namespace std;
    int main()
    {
        int x = SumFromTo( nReadNumber(), nReadNumber());
        cout << "the sum = " << x << endl;
        return 0;
    }
    

    In file io.cpp

    int nReadNumber()
    {
        cout << "Enter a whole number: ";
        int x;
        cin >> x;
        return x;
    }
    

    In file Calculate.cpp

    int SumFromTo(int nx, int ny)
        {
            cout << nx << " " << ny;
            int nValue = 0;
            for ( ;nx <= ny; nx++)
                nValue = nValue + nx;
            return nValue;
        }
    

    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?

  • derelove

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

  • Justin

    I have a question about the second solution to the quiz:

    int SumTo(int nSumTo)
    {
    int nSum = 0;
    for (int iii=1; iii <= nSumTo; iii++)
    nSum += iii;

    return nSum;
    }

    ————————————————-
    This looks like an infinite loop to me.
    If I were to declare int nSum = 3 then iii would be less than nSum. Therefore the value is true and you would increment iii. Then you add iii to nSum. So then nSum is now 5 and you will be testing to see if iii which now equals 2 is less than or equal to nSum. 2 = 1, the loop will increment iii and add it to nSum therefore testing to see if it is <=. iii will always be less than or equal to since you are incrementing it before you add it to nSum. I think the total sum should be a different variable and that you should not increment iii until after you have added it into the total sum. Here is what I produced and although it may not be small in size it works.

    —————————————————-

    #include "stdafx.h"
    #include
    using namespace std;

    void SumTo()
    {
    int nValue;
    cout <> nValue;
    int nSum = 0;

    for (int iii = 1; iii <= nValue;)
    {
    nSum += iii;
    iii++;
    }

    cout << "The total of all numbers from 1 to " << nValue << " = " << nSum << endl;

    }

    int main()
    {
    SumTo();
    }

    ——————————————————
    I just started taking these lessons three days ago and have already gotten here. I may be wrong but it is puzzling me. If you can explain this to me it would be greatly appreciated.

  • Deimantas

    Doesn’t the first solution need an identifier?
    int(iii);
    It didn’t compile until i added it.

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

     double NegativeExponent(int nBase, int nExp)
    {
    	double dValue = 1;
    	for (int iiii=0; iiii > nExp; iiii--)
    		{
    			dValue *= (1.0 / nBase);  // If I put in 1 instead of 1.0, it will do integer division!
                                                                    // And that is not what we want, right?
    		}
    
    	return dValue;
    }

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

     int main()
    
    cout << "Enter two integer values, one for int nBase, one for int nExp" << endl;
    cout << "nBase = ";
    int nBase = 0;
    cin >> nBase;
    
    cout << endl << "nExp = ";
    int nExp = 0;
    cin >> nExp;
    cout << endl;
    
    	if (nExp >= 0)
    	{
    		cout << "nBase ^ nExp = " << PositiveExponent(nBase, nExp);
    		cout << endl;
    	}
    	else
    	{
    		cout << "nBase ^ nExp = " << NegativeExponent(nBase, nExp);
    		cout << endl;
    	}
    
    cout << "If nBase ^ nExp = 0, then you have exceeded a very big or very small number ;) ";
    
    // This is some default code which I always have at the end of my main function.
    // The purpose of it is to wait for the user to press enter to quit the program.
    // If you need or want to use this piece of code, uncomment it.
    // Else, just leave it or delete it.
    
    /*
    	cout << endl;
    	cout << "Press enter to quit" << endl;
    	cin.clear();
    	cin.ignore(255, 'n');
    	cin.get();
    	return 0;
    */

    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:

       int main()
      {
      
      // rest of code here

      And the last piece of code should be:

      /*
      	cout << endl;
      	cout << "Press enter to quit" << endl;
      	cin.clear();
      	cin.ignore(255, 'n');
      	cin.get();
      */
      
      	return 0;
      } 

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

  • buffpony

    ok what i fail?
    #include
    using namespace std;
    int nValue;
    int looper;
    int SumTo(nValue)
    {
    cin >> nValue
    for(looper = 1; looper <= nValue; looper++)
    {
    nValue+=looper;
    return nValue;
    }
    }
    void main()
    {
    cout << "Type a number: ";
    SumTo(nValue);
    }

  • WCoaster

    You are adding nValue twice. Once at the very beginning and once at the end.

    Either use a different variable to accumulate the total or change:
    for(looper = 1; looper <= nValue; looper++)
    to
    for(looper = 1; looper < nValue; looper++)

    Either one should work.
    Should try and rework your code not to use global variable declaration.

    int SumTo(int x)
    { int y = 0;
    for (x; x > 0; x-=5)
    { y += x;
    cout << y << endl;
    }
    return y;
    }
    int main()
    { cout << " Enter a number: ";
    int value = 0;
    cin >> value;
    value = SumTo(value);
    cout << char(228) << " (1 to n) = " << value << endl;
    return 0;
    }

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


    int SumTo(int nVal)
    {
    int nResult = 0;

    // For nVal iterations, nResult = nResult + nVal
    // Then decrement nVal by 1 and loop
    // So 0 + 5, then 5 + 4, then 9 + 3, etc...
    for (; nVal > 0; nVal--) // omitted expr1, don't need it!
    nResult += nVal;

    return nResult;
    }

    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!

  • Moogie

    Damn formatting. I can’t edit it? :( Oh well.

  • Shishka

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

    
    #include <iostream>
    #include <iomanip>
    
    using namespace std;
    
    int main()
    {
        int nMax;
        cin >> nMax;
        long long nSum = (nMax*((nMax+1)/static_cast<long double>(2.0)));
        cout << setprecision(20) << nSum << endl;
    }
    

    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! :P

  • Iodream

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

    Code:

    #include "stdafx.h"
    #include <iostream>
    #include "conio.h"
    
    void WritePerfectNumbers()
    {
    	using namespace std;
    	int nTotal=0; // helps to keep track of the divisible numbers
    	cout << "1"<< endl;
    	for (int nCurrentNumber=2;nCurrentNumber<100;nCurrentNumber++) // starting with 2
    		{
    			for (int iii=1;iii<nCurrentNumber;iii++)
    				if (nCurrentNumber % iii == 0)
    					nTotal+=iii;
    			if (nCurrentNumber == nTotal)
    				{
    					nTotal=0;
    					cout << nCurrentNumber << endl;
    				}
    		}
    }
    
    int main()
    {
    	using namespace std;
    	cout << "The folowing program prints all perfect numbers from 1 to 100." << endl;
    	getch();
    	cout << endl;
    	WritePerfectNumbers();
    	getch();
    	return 0;
    }
    

    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.

  • vdarth53

    For problem # 2, I am not getting the correct output. What is wrong in this logic? Can anyone help me please?

    #include

    using namespace std;

    int SumTo(int nvalue)
    {

    for(int iii=0; iii<nvalue; iii++)
    {

    nvalue+=iii;
    }
    return nvalue;
    }

    int main()
    {

    int nvalue;
    cout<>nvalue;

    int sum;
    sum= SumTo(nvalue);
    cout<<"the result is "<<sum;
    return 0;
    }

  • Amjadb

    Hi , you wrote :
    for (int iii=0; iii < 10; iii++)
    cout << iii << " ";
    and then you said it prints 0 , how comes it prints 0 and the cout statement is after the iii++

  • Mindstormscreator

    I couldn’t figure out the last challenge and I tried running it… couldn’t close the terminal haha

    I never would have caught that

  • Bao Nguyen

    Can u tell me why “return nValue” is here?

    int Exponent(int nBase, int nExp)
    {
        int nValue = 1;
        for (int iii=0; iii < nExp; iii++)
            nValue *= nBase;
     
        return nValue;
    }

    Thanks

  • Zereso

    So far I have found this tutorial pretty easy to follow but this page is confusing the hell out of me.

    I’m not understanding the exponent function or quiz question 2.

  • jculleton

    I played for a while and made a little something out of the example loop;

    // testloop.cpp : Defines the entry point for the console application.
    //

    // #include “stdafx.h”
    #include
    #include
    using namespace std;

    int Exponent(int nBase, int nExp)
    // returns the value nBase ^ nExp

    {
    int nValue = 1;
    for (int iii=0; iii < nExp; iii++)
    nValue *= nBase;
    cout<< nValue;
    return nValue;

    }
    int main()
    {
    int nBase = 0;
    int nExp = 0;
    cout<< "input base number"<> nBase;
    cout<< "input exponent number" <> nExp;
    cout << " " << endl;

    Exponent(nBase, nExp);
    //cout<< nValue;
    }

  • jculleton

    for some reason the includes are blank….
    #include
    #include
    they should be between “<" and be iostream and cmath.

  • pavel1135

    Hello!

    I tried to do quiz problem 2 (Write a function named SumTo() that takes an integer parameter named nValue, and returns the sum of all the numbers from 1 to nValue) with static variables and recursion (just out of curiosity). Here is my code:


    int Sum(int nValue)
    {
    static int nCounter = 0;
    static int nSum = 0;
    nCounter += 1;
    nSum += nCounter;
    if (nCounter == nValue)
    return nSum;
    else
    Sum(nValue);
    }

    In this case function returns the same number as nValue instead of doing the summation form 1 to nValue.

    I tried to check what is going on with my static variables by printing them:


    int Sum(int nValue)
    {
    static int nCounter = 0;
    static int nSum = 0;
    nCounter += 1;
    nSum += nCounter;

    cout << nCounter << 't' << nSum << endl;&lt

    if (nCounter == nValue)
    return nSum;
    else
    Sum(nValue);
    }

    This time it returned the correct result.

    It looks like at first the nSum was not preserved or it was initialized to zero every every time the function was called. But when I entered cout << nCounter << 't' << nSum << endl; it somehow made the nSum value to stay.

    Can somebody explain me what is going on?

    Thank you!

  • DarkmoonBlade

    hay everyone here is an improved solution for quiz #2

    #include

    int sumTo (int nValue)
    {
    using namespace std;
    int nTotal = 0;
    for (int iii = 1 ; iii <= nValue ; iii++ )
    {
    nTotal = nTotal + iii;
    if (iii == nValue)
    {
    cout << iii;
    }
    else
    {
    cout << iii << "+";
    }
    }
    cout << " = " << nTotal;
    }

    int main ()
    {
    using namespace std;

    cout <> nValue;

    sumTo(nValue);
    }

    //:)

  • Bogdan

    Here is another variant of quiz #2:

    int SumTo (int x)
    {
    int y=0;
    for (; x > 0; x–)
    y += x;
    return y;
    }

You must be logged in to post a comment.