- 2

Loop

#include <iostream> using namespace std; int main() { int a=2; for(;;a+=a) { if (a>5) break; } cout<<a; return 0; } ans is 8 ..plz explain ... m nt getting it

23rd Oct 2016, 5:30 PM
zoom
zoom - avatar
3 Réponses
+ 2
you have not given condition in *for* but in the *if* you have given condition to give output only when a>5 so when it run a+a =2+2=4 but it is not output as your condition so again a+a=4+4=8 is your final output
23rd Oct 2016, 5:40 PM
Yashwant Kumar Sonkar
Yashwant Kumar Sonkar - avatar
+ 1
The for-clause is executed 3 times. a+=a means: a=2 a+=2 // result 4 a+=4 // result 8 You should restructure the loop and let the break-condition be inside the for-statement: for{/*variable initialization*/;/*condition for break*/;/*iteration rule*/) so that: for(;a>5;a+=a) {} "a+=a" means "a=a+a" so that's probably not what you wanted.
23rd Oct 2016, 5:42 PM
Ullrich Franke
Ullrich Franke - avatar
+ 1
thank u guys ..:)
23rd Oct 2016, 5:45 PM
zoom
zoom - avatar