C Program to Check Even or Odd Number

In this article, we are going to learn about how to Check whether a Number is Even or Odd by using the C program.
We will ask the user to enter a number and then we will learn multiple ways to check if a number is even or Odd.

1. C Program to Check Even or Odd


In this example, we are taking an integer input from the user. We will save it in integer. Then we will evaluate this number by using the % operator. We will try to find the remainder of this number by dividing it by 2. If the remainder is 0, then it means the number is even. If the remainder is not 0, then it is an odd number. We will make use of the if-else statement to print the results of even or odd number identification. Let us understand this with a code example.

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

    if(num % 2 == 0)
    {
        printf("The number %d is even.", num);
    }
    else
        printf("The number %d is odd.", num);
    
    return 0;
}

Output

Please enter an integer: 13
The number 13 is odd.

2. C Program to Check Odd or Even Using the Ternary Operator


In this example, we are also trying to evaluate if the number entered by the user is even or odd. In this example, we are making use of the ternary operator. This operator makes code more compact as compared to the if-else statement. In the single statement, we can get the expected results.

Let us understand how the ternary operator works. First, we will check the remainder of the number entered by the user when we divide it by 2. If the remainder is 0 then we use ? to print the even message. But if the remainder is non 0 then we print the message after the : operator.

#include <stdio.h>

int main() 
{
    int num;
    printf("Please enter an integer: ");
    scanf("%d", &num);
    
    (num % 2 == 0) ? printf("The number %d is even.", num) : printf("The number %d is odd.", num);

    return 0;
}

Output

Please enter an integer: 34
The number 34 is even.