Question:

I need help in a C++ question?

by  |  earlier

0 LIKES UnLike

include <iostream>

using namespace std;

int main ()

{

int accu = 0;

int x;

for (x =10; x<=15; x++)

{

if (x >13)

continue;

accu = accu + x;

}

cout << x << " " << accu << endl;

return 0;

}

....I know that the answer is 16 46...but i want to know why?

thanks

 Tags:

   Report

2 ANSWERS


  1. when continue is executed, the flow of the program goes directly to the x++ and then the evaluation x &lt;= 15.  Every thing below continue is not executed.  So x is 16 because it was incremented and is greater than 15 and the for loop exits, but x was declared outside of the for loop.  The code block inside the for loop was never executed after continue so no addition took place.  I&#039;m not sure where the 46 comes from...

    --I really blew it, let me try again.  I got caught on the if statement.  The line immediately below the if statement is evaluated only when if is true.  That is why it is helpful to use brackets {} after the if statement to include what you want to process when it true.  So....

    if(x &gt; 13)

          continue   //only is executed when if statement is true

    accu = accu +x   //this statement will always be executed.

    so 10 + 11 + 12 + 13 = 46 and this is assigned to accu and is declared outside of the for loop and is printed out.  Like wise x is declared outside the for loop and 16 is greater than 15 and the for loop ends. Therefore you get 16 for value of x and 46 for the value of accu.  Sorry for the wrong analysis earlier.

    --My earlier statement of continue was valid.  I used Visual Studio 2008 Express Edition and walked through it with the debugger.  You&#039;ll find this very handy debugging your code and understanding what it is doing.


  2. I&#039;m bored so I guess i can answer you.

    let take a look at your if statement it reads if x is greater than 13 then go back to the beginning of the for loop.

    the next statement is to add accu to x which it does only while x is less then 13 since it is following the if statement

    so accu is added to x until x reaches 14 and once x reaches 14 it keeps going back to the top of the for loop. and it is no longer adding x to accu because its never going pass the if statement after that.

      

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.