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 (Retired) Functional Programming in C Conditionals

How do you chain multiple if statements?

IOS Development, Functional Programming in C, Conditionals Quiz. On the conditionals quiz I can't seem to find out how to chain multiple if statements.

1 Answer

Alex Uribe
Alex Uribe
2,481 Points

So the important thing to understand about if statements is that you can have multiple cases. If you only have 1 case that you're checking for (e.g. if (x) {//do y} ) then you don't use an else clause. If you have two cases, you have at least two options:

<br />

  1. write if/else statements -

<br />

if (x) {
// do y
} else {
// do z
} 

<br />

  1. write if/else if statements -

<br />

if (x) {
// do y
} else if (v) {
// do z
}

<br /> The difference between these two is that you are specifying that you need some expression 'v' to be true to 'do z' in option 2, whereas in option 1 you are writing a sort of catch-all that will handle any case not handled by the first if statement that's looking for some expression 'x' to be true in order to 'do z'. The purpose of 'else if' statements is to catch more cases before you hit the 'else' at runtime. For example, you can chain if statements like so:

<br />

if (a) {
// do b
} else if (c) {
// do d
} else if (e) {
// do f
} else {
// do z
}

<br /> Here, we have three clauses before we hit the 'else' case. The first being the 'if', and the other two being 'else if' statements. you can have as many of these 'else if' statements as you want before 'else' so that you can catch more conditions before else handles the rest that aren't handled.