Forgot username/password? Don't have an account?
Login with Facebook
Home » Courses » Conditionals 1 - 'if' » Else-if: dealing with multiple conditions
Subscribe for updates.
* New to us? log in with Facebook and get a free day pass

Else-if: dealing with multiple conditions

Checking is not always just for a YES or a NO. When there are more than 2 possibilities to be checked by the program logic, a special language construct is required: the “else-if” clause. There are many examples of this, but the most common are when you have a particular variable in your program that can have multiple values, or you have ranges of values, with different action(s) to be taken for each range.

In real life, we are often faced with situations where we need to have more than one option ready. Suppose the public (bus) transport can be used by giving change, and going from Brooklyn Bridge to Statue of Liberty in NYC costs half a dollar(a person can dream). Now, you could pay in cents, nickels, dimes or quarters, depending on what's jingling in your pocket. A passenger could reason:“If I have quarters, I give 2 of them. Otherwise if I have dimes, I give 5. Otherwise with nickles, 10 of them go. Otherwise if I'm loaded with pennies, out go 50. Else my butt is walking.”

The pseudo-code for the above change example could be written as:

if(denomination == “quarters”){

Change = 2Q;

}else if(denomination == “dimes”){

Change = 5D;

}else if(denomination == “nickels”){

Change = 10N;

}else if(denomination == “pennies”){

Change = 50P;

}else{

assWalking = true;

}

Lol thanks perfect example :)

The top-most if and subsequent else-if clauses check for specific conditions, or a specific combination of conditions. For the scenario where none of those conditions is met, the "else" clause is entered. The cascading else-if conditions must always be terminated by an "else" clause, for the “default” condition; i.e., if none of the conditions (if and else-if cascade) is true.

As in the case of if/else alone, only one of the conditions (or only the default case) will evaluate to true, so control can only branch to one of the clauses in the cascade. Actually, the behavior of the program control depends on what conditions the user has passed, but language ensures only 1 block runs .

Also, each else-if construct can have multiple operations, so curly brackets can be used for each clause in the cascade:

else if(denomination == “pennies”){

Change = 50P;

Busman = isPissed;

}

Got A Question?

'I love being Prime'

Have a question but don't want to ask it publicly? If you are a prime member just ask right here and we will get back to you within 48 hours. Not prime yet? no worries you can ask publicly below.

Act now while we have available seating

Our on line school is private, affordable and interactive with trainer support.
Act now save your seat before someone else takes yours.
Act now