When a programming situation requires the choice of one case from many different cases successive if statements can be tied together forming what is sometimes called an if-else-if ladder.
if ( condition_1 )
else if ( condition_2 )
else if ( condition_3 )
else if ( condition_n )
Essentially what we have here is a complete if-else statement hanging onto each else statement working from the bottom up.
For Example : Another guessing game.
int secret = 101, guess, count = 0 ;
printf( "\n Try and guess my secret number.\n\n" ) ;
while ( 1 ) // infinite loop until we break out of it
printf( "\n Make your guess: "" ) ;
scanf( "%d", &guess ) ;
count ++ ;
if ( guess < secret )
printf( "\nA little low. Try again." ) ;
else if ( guess > secret )
printf( "\nA little high. Try again.") ;
printf( "\nOk you got it and only on attempt %d.", count );
NOTE : Caution is advisable when coding the if-else-if ladder as it tends to be prone to error due to mismatched if-else clauses.
Conditional Operator :- ?:
This is a special shorthand operator in C and replaces the following segment
if ( condition )
with the more elegant
condition ? expr_1 : expr_2 ;
The ?: operator is a ternary operator in that it requires three arguments. One of the advantages of the ?: operator is that it reduces simple conditions to one simple line of code which can be thrown unobtrusively into a larger section of code.
For Example :- to get the maximum of two integers, x and y, storing the larger in max.
max = x >= y ? x : y ;
The alternative to this could be as follows
if ( x > = y )
max = x ;
max = y ;
giving the same result but the former is a little bit more succinct.