why is it that when I input 'a' as '2' in this short program, it gives me 'no output'. is there anything wrong with the if-statement nesting?. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

why is it that when I input 'a' as '2' in this short program, it gives me 'no output'. is there anything wrong with the if-statement nesting?.

int main () { int a; cin >>a; if (a==1){ cout<<"a is 1\n"; if (a==2){ cout<<"a is 2"; }} return 0; }

12th Sep 2016, 2:22 PM
Cody Arthur
Cody Arthur - avatar
3 Answers
+ 2
Your 'a==2' if statement is nested inside the 'a==1' if statement, so will only be reached if a=1 but will obviously never be true. Where you have the two closing curly braces, you need to move one of them to close the first if statement. if ( a == 1 ) { cout << "a is 1"; } if ( a == 2 ) { cout << "a is 2"; }
13th Sep 2016, 5:16 PM
Liam
Liam - avatar
+ 1
You're (a == 2) if statement is inside the (a == 1) if statement. Yours: if (a == 1) { cout << "a is 1"; if (a == 2) { cout << "a is 2"; } } How it should be: if (a == 1) { cout << "a is 1"; } if (a == 2) { cout << "a is 2"; }
12th Sep 2016, 3:24 PM
Cohen Creber
Cohen Creber - avatar
+ 1
thanks guys..
12th Sep 2016, 4:53 PM
Cody Arthur
Cody Arthur - avatar