+ 1

Why the first line of output is 2*1=0

#include <iostream> using namespace std; int main() { int a=1,b; while(a<=10) { cout<<"2*"<<a<<"="<<b<<endl; a=++a; b=2*a; } } Output: 2*1=0 2*2=4 2*3=6 2*4=8 ...... Why 2*1=0

12th Jan 2021, 5:45 AM
Jawahirullah
Jawahirullah - avatar
1 Answer
+ 3
Variable <b> is uninitialised in the first round of the loop. You need to move assignment of <b> before printing output. Uninitialised variables have arbitrary value. while(a <= 10) { b = 2 * a; cout << "2*" << a << "=" << b << endl; ++a; }
12th Jan 2021, 6:09 AM
Ipang