+ 1

Why does this code output 4?

#include <iostream> using namespace std; int main() { int x=1; for(int i=2; i>0; i--) { x+=i; } cout<<x; }

2nd Nov 2016, 1:46 PM
RainbowUnicornPrincess
RainbowUnicornPrincess - avatar
2 Answers
+ 1
x is 1 initially and I is 2 initially every time the loop runs I is decreased until it reaches 0 so, 1+2 = 3 I gets decreased and the new x value is 3 3+1 = 4 I gets decreased to 0 condition states I should be more than 0 so the code is not executed. hence answer is 4
2nd Nov 2016, 2:50 PM
Ziyaan Hassan
Ziyaan Hassan - avatar
0
the answer is 4
2nd Nov 2016, 3:15 PM
rahul sharma
rahul sharma - avatar