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);
5 Réponses
+ 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.
0
Are you sure you wrote this code, exactly? This seems to me like a textbook example for a do-while-loop.
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;
}
0
Thanks stefan and game coin for the response
unknowingly one more statement excuted
thanx again
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.