Previously, you learnt about if statement. The syntax was:

if (condition)
{
//This block will be executed if the condition is true
}

Adding else at the end of the if block will give a task to execute if the condition is false. Using else after if looks like:

if (condition)
{
//This block will be executed if the condition is true
}
else
{
//This block will be executed if the condition is false
}

The condition is given to the if statement and if that condition is true, the first block of code is executed and if that condition is false, the second block of code is executed.

Now let's dive into examples.

Write a program to input two numbers and display the greater one on the screen.

*Try this: What will happen if you give two equal numbers to the program?

Practice Corner:

  • Write a program to input two numbers and display the smaller one on the screen.
  • Write a program to input a number and display "OK" if the number is 100 otherwise display "Not OK"
  • Write a program to input the distance traveled by a passenger in a train and calculate the fare. The fare is calculated as follows: If the distance traveled by the passenger is less than or equal to 5km, a fixed fare of 5$ will be charged. And if the distance is greater than 5km, the fare will be charged at the rate of 0.9$ per km