Skip to main content

8. If and else-if Statements

 

C if-else Statement

The if-else statement in C is used to perform the operations based on some specific condition. The operations specified in if block are executed if and only if the given condition is true.
There are the following variants of if statement in C language.

  1. If Statement
  2. If-else Statement
  3. If else-if ladder
  4. Nested if

If Statement

The if statement is used to check some given condition and performs some operations depending upon the correctness of that condition. It is mostly used in the scenario where we need to perform the different operations for the different conditions.

#include <stdio.h>

int main()
{
   int number = 0;
   printf("Enter a number : ");
   scanf("%d", &number);
   if (number % 2 == 0){
      printf("%d is even number.\n", number);
   }
   return 0;
}

Output :

Enter a number : 4
4 is even number.
Enter a number : 5

Program to find the largest number of the three

#include <stdio.h>

int main()
{
   int a, b, c;
   printf("Enter three numbers : ");
   scanf("%d %d %d", &a, &b, &c);
   if (a>b && a>c){
      printf("%d is largest.\n", a);
   }
   if (c>a && c>b){
      printf("%d is largest.\n", c);
   }
   if (a<b && b>c){
      printf("%d is largest.\n", b);
   }
   if (a==b && a==c){
      printf("All are equal");
   }
   return 0;
}

Output :

Enter three numbers : 5 6 8
8 is largest.

If-else Statement

The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition.

#include <stdio.h>

int main()
{
   int number;
   printf("Enter a number : ");
   scanf("%d", &number);
   if (number % 2 == 0){
      printf("%d is even number.", number);
   }
   else{
      printf("%d is odd number.", number);
   }
   return 0;
}

Output :

Enter a number : 4
4 is even number.
Enter a number : 5
5 is odd number.

Program to Check Whether a person is eligible to vote or not

#include <stdio.h>

int main()
{
   int age;
   printf("Enter your age : ");
   scanf("%d", &age);
   if (age >= 18){
      printf("You are eligible to vote....");
   }
   else{
      printf("Sorry .... you can't vote");
   }
   return 0;
}

Output :

Enter your age : 19
You are eligible to vote....
Enter your age : 12
Sorry .... you can't vote

Comments