If Else Statements

else - to execute code block if condition is not met.

else if - to check alternative condition if the main one is false.

Syntax

else

else if

Else Example

Let's look at a program that checks whether speed is above or below the speed limit for cities (50 km/h).

Output:

Since the condition at line 4 is false, the code inside else block executes.

Else If Example

Let's have a program that categorizes a person depending on his/her height.

Rules are the following:

  • below 160cm - short
  • between 160cm to 185 cm - medium
  • above 185 cm - tall

Output:

Since the condition at line 4 is false and the condition at line 7 is true, the code inside else if block executes.