C program to check whether a number is even or odd

In this C program we will learn how to check whether a number entered by a user is even or not. An even number is a number that can be divided by 2 completely. For example – 2,4,12,16 etc. An odd number is the vice versa of an even number.

Consider the below program –

Program

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

Output

Enter a number24

The number is even

Explanation

  •  After including the necessary header file ‘stdio’, first of all, we have declared an integer type variable named num inside the main function. Inside this variable we will store the number given by the user.
  •  Then with the help of printf function, we are displaying a message to the user that says “Enter a number”. Essentially, this is very first thing that would be displayed when the program is executed.
  •  By the scanf function we have collected the value given by the user and stored it in the variable ‘num’. Next we have put if …. else blocks. Inside the if statement we have mentioned a condition that would check if the number is even. If it is so, the condition of the if statement becomes true and a message would be displayed that says – “The number is even”.
  • If the condition of the if statement becomes false (if the user entered a number that is not divisible by 2), the else part would be executed displaying a message that says – “The number is odd”.
  • The program terminates with the return 0 statement.

Note : In if….else block the else part is a default part. We do not need to place any condition inside the else part. The else part would only execute if the condition inside the ‘if’ block become false.