You learnt about if statement. This lesson is just an add-on to what you have already learnt. Let us consider if you want to test multiple conditions on the same thing. The first way to do this is by using multiple if statements.
Let us consider a problem for understanding. Our program should input the age for the candidate and if the age is greater than 16, it should display eligible otherwise, it should display not eligible. Also if the age entered is less than 0 (which is not the right input) the program should display error.

Let us solve the above problem by using multiple if statements.

The problem can also be solved by using if statement inside another if statement (so called "nested if statement")

The best method to solve this problem is by using else if. It is the best because it makes our code "easy to read and easy to understand". The syntax of else if is as follows:
if (condition1)
{
/*This block will be executed if the condition1 is true*/
}
else if (condition2)
{
/*This block will be executed if the condition1 is not true but the condition2 is true*/
}
else if (condition3)
{
/*This block will be executed if the condition1 and condition2 are false but the condition3 is true*/
}
else
{
/*This block will be executed if none of the above conditions is true*/
}
*In the above example, I have used two else if statements. You can use as many as you want
**else if statement is always used between if and else. It can not be used independently.
***It is not necessary to add the last else statement

Now let's solve the problem using else if


Now let's extend the above problem. Our program should now input the age and if the age is between 17-30 it should display eligible. If the age is below this range, it should display too young and if the age is above this range, it should display too old. If the age is above 100, it should display wow. If the input is wrong i.e. less than 0, it should display error.

Note: Try to write the code for this yourself first and then see the solution below.





Practice Corner:

  • Write a program to input two numbers. The program should tell if the first number is equal to, greater than or less than the second number.
  • Write a program to input the percentage of a student and tell his grade. 90-100=A+ , 80-89=A , 70-79=B , 60-69=C , 50-59=D , 30-49=E , 0-29=F