Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Objective-C Basics Introduction to Operators and Conditionals Review IF ELSE

Edson Ramirez
Edson Ramirez
1,044 Points

Shouldn't the answer be ages 65 and over, since the code doesn't use else if. It uses if a second time.

That should cause the code to skip the second if, and charge everyone over 13 ten dollars. People 65 and over wouldn't get their discount.

1 Answer

Kevin D
Kevin D
8,646 Points

When the code is run, the computer reads all the lines from top to bottom and will carry out all the code that was written (unless you specified to end the function after the first condition).

So when it reads the first if statement

 if(customerAge < 13){
        ticketPrice = 5.00;
    }

It will check the condition; if it's true, it will run the code inside the statement and then go to the next line of code; if it's false, it will ignore the code inside the if statement but it will also move on to the next line of code as you haven't specified whether to end the function if false or not.

Because of this (you haven't ended the function), the next if statement will be read and the conditions checked. This is bad, as it could override any of the previous logic you had written which will cause problems!

It's like creating a smoothie: Imagine you want to create a banana smoothie and the if statement checks how hungry you are to determine the number of bananas you use.

int hungryLevel; 
int numberOfBananas = 0; // we start off with no bananas

hungryLevel = 50; // we set our hungryLevel at 50

if (hungryLevel < 60) { // we check to see if our hungry level meets the conditions - it does!
numberOfBananas = 2;
}
// because our condition returns true, after the first if statement, the number of bananas used will be 2
// however, since we do not end the function, or specify how to handle the code after this is true, the next lines of code will be run!

if (hungryLevel == 50) { // so now this if statement will be checked...but oh no - that's a lot of bananas!! but this condition is also true
numberOfBananas = 10; // so the number of bananas will now be 10 and we have overrode our previous logic 
} else {
numberOfBananas = 5;
}