C Program to Check Whether a Number is Even or Odd

The number is Even or Odd Program in C

We can determine whether a number is Even or Odd program in C. This can be tested using different methods. The test can be done using simple methods such as

  • Testing the number’s divisibility by 2.
    • If the remainder is zero, the number is even.
    • If the remainder is not zero, then the number is odd.

The following algorithm describes how a C program can test if a number is even or odd.

Example :

Number is 24
It is an even number because it is exactly divisible by 2
i.e 24 % 2 -> 0 (leaves no remainder on modulus/remainder operator)

Number is 15
It is odd number because it is not divisible by 2
i.e 15 % 2 ->1 (leaves 1 remainder on modulus/remainder operator) 
Program to check if a number is even or odd
Time ComplexityO(1)
Space ComplexityO(1)

Method 1

For user input number

  • If number % 2 == 0
    • If true then the number is even
    • Else, the number has to odd

Here % is called as modulo/remainder operator

Code

Run
#include <stdio.h>

int main ()
{
    int number;
    printf ("Insert a number \n");
    scanf ("%d", &number);

    //Checking if the number is divisible by 2
    if (number % 2 == 0)
        printf ("Even");
    else
        printf ("Odd");
  
    return 0;
}

Output

Insert a number
10
Even

Method 2

For this method, we use the ternary operator in C

For user input number

  • If number % 2 == 0
    • If true then the number is even
    • Else, the number has to odd

Here % is called as modulo/remainder operator

Code

Run
#include <stdio.h>
int main ()
{
    int number;
    printf ("Insert a number \n");
    scanf ("%d", &number);
    
    //Checking if the number is divisible by 2
    number % 2 == 0? printf ("Even"):printf ("Odd");
    
    return 0;
}

Output

Insert a number
15
Odd

Method 3

For this method, we use the bitwise operator, in this case, bitwise and (&) How this works is below
  • For any number following operation : (num & 1) will always result
    • 1: If num is odd
    • 0: if num is even
Let’s see how
// 5 (in binary) : 00000101 
// 1 (in binary) : 00000001

    0 0 0 0 0 1 0 1

  & 0 0 0 0 0 0 0 1

  - - - - - - - - -

    0 0 0 0 0 0 0 1

Code

Run
#include <stdio.h> 

// Returns true if n is even, else odd
int isEven(int num)
{
    // num & 1 is 1, then odd, else even
    return (!(num & 1));
}
 
// Driver code
int main()
{
    int num;
    printf("Enter the number: ");
    scanf("%d",&num);

    isEven(num)? printf ("Even"):printf ("Odd");
 
    return 0;
}

Output

Insert a number
5
Odd

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Getting Started