If else Statements in C

Sometimes we want to execute take a decision based on whether a condition is true or false. For example - If it's raining, stay home otherwise go outside. In programming also, we may want to execute different statements based on a condition e.g. if a > b, then do this otherwise do that. This is done by using the if-else statements.

Syntax of If else Statements

if(condition is true)
{
    //Statements
}
else  // condition is false
{
    //Statements
}
    
If there is a single statement following if or else then we can skip the curly brackets.

Example


#include <stdio.h>
void main()
{   
  int cost;
  printf("Enter cost: ")
  scanf("%d",&cost);

  if(cost <= 400)
  printf("Buy");
  else
  printf("Do not buy");
}   
    
If the condition is true i.e the cost <= 400 then Buy would be printed otherwise Do not buy will get printed.

Output 1

Enter cost: 400
Buy
    

Output 2

Enter cost: 600
Do not buy
    

If else if Ladder

It is used to check multiple conditions. The syntax is as follows :
if(condition1 is true)
{
    //Statements
}
else if(condition2 is true)
{
    //Statements
}
else  // if none of the conditions is true
{
    //Statements
}
    
Suppose you want to assign grades to students based on their marks. You can do it by using if else if for checking multiple conditions.

#include
void main()
{
  int marks;
  printf("Enter your marks : ");
  scanf("%d",&marks);
  char grade;

  if(marks > 80 && marks <= 100)
  {
    grade='A';
  }

  else if(marks > 60 && marks <= 80)
  {
    grade='B';
  }

  else
  {
    grade='C';
  }

  printf("Your grade is %d",grade);
}
    

Output

Enter your marks : 45
Your grade is C
    

Ternary Operators

It is a shorthand form of if else. If the condition is true then the statement after the ?(question mark) is executed otherwise, the statement after :(colon) is executed.Consider the following example.

#include<stdio.h>
void main()
{
  int a,b;
  printf("Enter the value of a and b:");
  scanf("%d %d",&a,&b);

  int c=(a>=b)?(a):(b);
  printf("Largest value = %d",c);
}
    

Output

Enter the value of a and b: 2 5
Largest value = 5