Trying to understand where the else is to the if statement in the adult part. Is there not one and just closed by the } | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Trying to understand where the else is to the if statement in the adult part. Is there not one and just closed by the }

int age = 18; if (age > 14) { if(age >= 18) { cout << "Adult"; } else { cout << "Teenager"; } } else { if (age > 0) { cout << "Child"; } else { cout << "Something's wrong"; } } and why does the program mess up if you put the adult part first?

19th Nov 2017, 1:38 PM
Terry Smart
3 Answers
+ 1
The block where it calls cout << "Teenager"; is the else block of adult block. Tips: if you're on the mobile app you can tap to have the cursor near a curly brace and Code Playground will turn the brace color yellow if it is equally paired, and red otherwise. What do you mean by program mess up?
19th Nov 2017, 4:24 PM
Ipang
+ 1
If you have more than one line of code following an if statement it is recommended that you surround the block with pair of curly braces. Let's review your code; // Assuming age = 18 if (age > 18) //false, age=18, not >18 { //these are not executed however, look above if (age > 14) //true, 18 is > 14 cout << "teenager"; //then you get this else cout << "adult"; //rather than this }
19th Nov 2017, 4:48 PM
Ipang
0
if you put the if (age > 18) if (age > 14) cout << "teenager"; else { cout << "adult"; messes up the program where it doesn't make the right choice.
19th Nov 2017, 4:32 PM
Terry Smart