If Else statement in C With Examples

If Else statement in C With Examples

In C Program, if else statement is also known as the conditional statement. It is used when we want to perform some operation on the basis of conditions. Or we can say we use this for conditional execution of code based on a given condition. This means once the condition is satisfied then only execute the statement otherwise not.

Syntax of If-else statement

if (conditions) 
{
   // this block code to execute if the condition is written in if true
} else {
    // this block code to be executed if the condition is written in if false
}

Explanation of the above syntax

  1. In the bracket of the if condition, there is an expression written which is evaluated to be either true or false.
  2. If the condition is true, It means the expression written in brackets is returning a true value. If the value is true the code written in the curly brackets of the if block will be executed.
  3. If the condition is false, the code inside the else block will be executed.
  4. The “else” keyword is optional. We can only use the if statement if we want to execute the code only when the condition is true,

Program 1: C Program to demonstrate if the statement

#include <stdio.h>
int main() {
  int num;
  printf("Enter a number: ");
  scanf("%d", &num);
  if (num < 50) {
    printf("If statement executed");
  }
  return 0;
}

Output

Enter a number: 44
If statement executed

Explanation of the above program

In the above example, the program compares the value of the variable num with 50. If num is smaller than 50, then our program will print “If statement executed”. Here there is no else statement so nothing will be printed.

Program 2: C Program to demonstrate if else statement

#include <stdio.h>
int main() {
  int num;
  printf("Enter a number to check even or odd: ");
  scanf("%d", &num);
  if (num%2==0) {
    printf("Given number is even");
  }else{
    printf("Given number is odd");
  }
  return 0;
}

Output

Enter a number to check even or odd: 45
Given number is odd

Explanation of the above program

In the above example, the program checks the given number is even or not. In the braket of if statement we have written the expression to check number is even. If expression will return true then the if block will be executed. And it will print the output “Given number is even”.

And If the expression inside if will return false, then else block will execute and our program will print “Given number is odd”.

That’s a detailed explanation of the “if-else” statement in C. It allows you to control the flow of your program based on certain conditions that enables you to execute different blocks of code as needed.