C else if Clause

Till now we have learnt about the if statement, if-else statement, if-else nested statements and logical operators. Logical operators are good alternatives of nested if-else statements. But there are still some cases when we have to use nested if-else clause. So to make those situations a bit easy, Dennis Ritchie introduced else if clause.

What are else if clause?

Well they are no major difference between nested if-else and else if clause. As I told you earlier, the main problem with nesting is that it makes the program difficult to read. So to avoid that issue, else if clause is introduced.

General Syntax of else if clause is given below.

if (condition)
{
Statement 1
Statement 2 and so on
}

else if (condition)
{
Statement 1
Statement 2 and so on
}

else if (condition)
{
Statement 1
Statement 2 and so on
}

else
{
Statement 1
Statememt 2 and so on
}

Things to remember while using else if clause

  • You can use any number of else if clause in this ladder.
  • Usage of else in the last is completely optional. It means its up to you that you either want to include it or not in your program.
  • This does not destroy the readability of the program.
  • By using else-if clause, our program does not creep to the right due to indentation.

Remember by using else if clause, no change will occur in the execution of program. It is just the re-write of nested if-else clause. You can understand this point by watching below example.

C else if Clause

Lets try to understand this clause with one program.

Question: Make one program to check the eligibility of student to take admission in a college. The student must fulfil at least one condition to take admission in the college.

  • Student should be male. His marks should be more than 80% in 12th and his age should be at least 18 years.
  • Student should be female. Her marks should be more than 75% in 12th and her age should be at least 17 years.
  • Student should be played at any national level game. Age and qualification doesn’t matter in this case.

Output

Output

Explanation

  • In the beginning we gave some instructions to user that how he/she should enter the data in our program.
  • After that we printed the message and take some details from the student.
  • Now basically we have 2 conditions. At first we have to check the student if he/she eligible for general kota and in the last we have to check if he/she is eligible for sports kota.
  • To make things a bit clear I checked the results for general kota by using if keyword. I combined the conditions by using logical operators to make the program a bit compact.
  • After that by using else if clause I have checked if the student is eligible for sports kota.
  • If nothing works then I have also given the default else block to print the message “You cannot take admission in our college.”

Leave a Reply

Your email address will not be published. Required fields are marked *