hi, me newbie, started last day, right now I wrote a code using "do", the out is 2,4,6, while condition is <5. why or how output is exceeding 5. thanx in advance int a=2; do { cout<<a <<endl; a+=2; } while (a <5); | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
0

hi, me newbie, started last day, right now I wrote a code using "do", the out is 2,4,6, while condition is <5. why or how output is exceeding 5. thanx in advance int a=2; do { cout<<a <<endl; a+=2; } while (a <5);

25th Jun 2016, 5:38 PM
Abdullah
Abdullah - avatar
5 ответов
+ 2
a = 2 first iteration of loop: cout << 2 << endl; a = a + 2 = 2 + 2 = 4 a < 5 ? yes. then: second iteration of loop: a = 4; cout << 4 << endl; a = a + 2 = 4 + 2 = 6 a < 5 ? no. then: break loop. note that the value of a is 6 now.
25th Jun 2016, 6:04 PM
Garme Kain
Garme Kain - avatar
0
Are you sure you wrote this code, exactly? This seems to me like a textbook example for a do-while-loop.
25th Jun 2016, 5:51 PM
Stefan
Stefan - avatar
0
exacly but my mistake #include <iostream> using namespace std; int main () { int a=2; do { cout<<a <<endl; a+=2; } while (a <5); cout <<a <<endl; <--this one return 0; }
25th Jun 2016, 6:06 PM
Abdullah
Abdullah - avatar
0
Thanks stefan and game coin for the response unknowingly one more statement excuted thanx again
25th Jun 2016, 6:13 PM
Abdullah
Abdullah - avatar
0
It checks condition after printing. #include <iostream> using namespace std; int main() { for(int x = 2; x < 5; x += 2) {cout<<x<<endl;} return 0; } //Outputs: //2 //4 This code checks it before printing.
26th Jun 2016, 5:11 PM
Christian Roos
Christian Roos - avatar