if else statement in c


  • The if statement lets you do something if a condition is true. If it isn’t true, nothing happens. But suppose we want to do one thing if a condition is true, and do something else if it’s false.
  • While if performs an action only when its condition evaluate to true, if / else allows you to specify the different actions when the condition true and when the condition is false.
  • The else statement cannot be used without if. No multiple else statements are allowed with one if.
  • The if statement lets you do something if a condition is true. If it isn’t true, nothing happens. But suppose we want to do one thing if a condition is true, and do something else if it’s false.
  • That’s where the if...else statement comes in. It consists of an if statement, followed by a statement or block of statements, followed by the keyword else, followed by another statement or block of statements.
  • As a general rule, we express a condition using C's relational operators.
  • Syntax:

    if(condition) 
    {
       // Statements inside body of if
    }
    else 
    {
       //Statements inside body of else
    }
    Flow Diagram of if else statement

    Fig- Flow Diagram of if else statement

Example:

/ Program to check whether an integer entered by the user is odd or even

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

    // True if remainder is 0
    if( number%2 == 0 )
        printf("%d is an even integer.",number);
    else
        printf("%d is an odd integer.",number);
    return 0;
}

Output:

Enter an integer: 7
7 is an odd integer.