C If else Statement

In this lesson, you will learn about the if-else statement and its usage, along with examples to better understand the topic.

If-else Statement in C

The if-else is another conditional statement in C. You can use the if-else statement if you want to perform a block of code for the true condition and another block for the false condition.

Syntax of if-else Statement in C

if (condition is true) {
  //block one will be executed if condition is true
} else { // false
  //block two will be executed if condition is false
}

Flow chart of if-else statement in C

 

Example of if-else statement in C

#include <stdio.h>

int main() {
  int var;
  printf("Please enter number: ");
  scanf("%d", &var); // takes the input
  // true if input is divisible by 2
  if ((var % 2) == 0) {
    printf("The number you entered is divisible by 2.\n", var);
  } else {
    printf("The number you entered is not divisible by 2.\n", var);
  }
  return 0;
}

Output

Please enter number: 100
Come in this block if input is divisible by 100

If you run the program again and enter 97 instead, the code in the ‘else’ part will be executed.

Please enter number: 99
The number you entered is not divisible by 2

Explanation of the code

The program asks the user for the input; if the statement (var % 2) == 0 is true, the first code block will be executed. Otherwise, the code in the ‘else’ part will be executed.

In the next lesson, you will learn about the if...elseif...else statement in C.