What is correct code to print 2 4 6 8 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is correct code to print 2 4 6 8

#include <iostream> using namespace std; int main() { int a; cout<<"enter the value ofa:"<<endl; cin>>a; while(a<10) cout<<"a= \n"<<a; a=a+2; return 0; } Why its output is not as i thought?

12th Jan 2021, 4:05 AM
Jawahirullah
Jawahirullah - avatar
2 Answers
+ 3
while (a < 10) { if (a % 2 == 0) { cout << a; } a++; }
12th Jan 2021, 4:12 AM
A͢J
A͢J - avatar
+ 1
You should wrap the while-loop body in curly brackets, otherwise the loop may become infinite, because only the first line following the while-loop head will be executed, and <a> is not getting incremented. And even by fixing that, output depends on the input.
12th Jan 2021, 4:14 AM
Ipang