show method .

\

What is the output of the following program?

#include <iostream>
using namespace std;
int main() {
int i,x;
for(i = 5; i > -10; i--)
x = i + 2;
cout << ++x << " ";
return 0; }
a. -6
b. 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6
c. 8 7 6 5 4 3 2 0
d. None of the above




I have doubt when there is no brace after for loop state.
I used to get -8 but none of them is -8 so what is the right ?

+can you explain the detailed method ? .

thanks .

Last edited on
Explanation of the effect of the brace: http://www.cplusplus.com/doc/tutorial/control/

You could compile and run the program in order to see the output.
(That obviously does not help you comprehend the basic constructs in the code.)


How do you get the -8?
for(i = 5; i > -10; i--)
x = i + 2;
In here, actually you just need to see the last i in the for statement because x is equal to i + 2 where i will always change until -9
Simulation :
i = 5 -> x = 5 + 2 = 7
i = 4 -> x = 4 + 2 = 6
.
.
i = -9 ->x = -9 + 2 = -7
As you can see, x equal to -7 and your output is ++x, which mean you need to add 1 to x, which is x = -7 + 1 = -6

Therefore, x = -6(a)

Maybe you get -8 because you run your for until i = -10, then x will become -8 and you forget to plus 1, then your answer will be -8
//just my speculation

Nb : If there is no brace after loop state, you can just run the program below it
example :
for(int i = 0;i < 10;i++)
x++;
....
then it will only run x++;
Last edited on
last night I figured out my mistake after another trial but your explanation was very helpful and made me sure more about the right answer.

thanks a lot for your time.

have a nice day.
Topic archived. No new replies allowed.