Conditional statements are used to perform different actions based on different conditions. The if statement is one of the most frequently used conditional statements. It is given a condition and if that condition is true, the block of code inside the if statement is executed otherwise, it is not executed.

Important term: Block of code: Any code enclosed in curly brackets { } is called a block of code.

The syntax for if statement is:

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

The condition in the if statement is actually a conditional expression. Remember that a conditional expression is an expression that gives a boolean (true or false) as output. For example 4 > 6 and 9==(8+1) are conditional expressions because they evaluate to either true or false.
Relational and logical operators are used to create a conditional expression. Let's take an example on if statement.

Let's write a program that is a bit more practical. The program will input a number and if that number is greater than 100, it will display something on the screen.
Its output:
Let's try for another input:

Let's take another example. A program that will input two numbers and display "Yes" on the screen if the product of two numbers lies between 100 and 200
*Notice the line number 11. If a number lies between 100 and 200, it must be greater than or equal to 100 and less than or equal to 200. This is what we used in the condition of if statement.

Its output:
*As the product of 30 and 5 i.e. 150 is between 100 and 200, so "Yes" was displayed on the screen.

Output for another input:
* As the product of 300 and 6 i.e. 1800 was net between 100 and 200, so "Yes" was not displayed on the screen.


Practice Corner:
  • Write a program that inputs a number and displays "odd" on the screen if the number is odd.
  • Write a program that inputs two numbers and displays "Yes" on the screen if the sum of two numbers is greater than 50.
  • Write a program that inputs two numbers and displays "Yes" on the screen if the product of two numbers does not lie between 100 and 200