You are here

Even or odd program in C

Odd even numbers

C programs to check odd or even using different methods. In the decimal number system, even numbers are exactly divisible by two while odd numbers are not. We can use the modulus operator '%' which returns the remainder, for example, 4%3 = 1 (remainder when four is divided by three).

Odd or even program in C using modulus operator

#include <stdio.h>

int main()
{
  int n;

  printf("Enter an integer\n");
  scanf("%d", &n);

  if (n%2 == 0)
    printf("Even\n");
  else
    printf("Odd\n");

  return 0;
}

Even odd C program

We can use bitwise AND (&) operator to check odd or even. For example, consider binary of 7 (0111), (7 & 1 = 1). You may observe that the least significant bit of every odd number is 1. Therefore (odd_number & 1) is one always and also (even_number & 1) is always zero.

C program to find odd or even using bitwise operator

#include <stdio.h>

int main()
{
  int n;
   
  printf("Input an integer\n");
  scanf("%d", &n);

  if (n & 1 == 1)
    printf("Odd\n");
  else
    printf("Even\n");
   
  return 0;
}

C program to check odd or even without using bitwise or modulus operator

#include <stdio.h>

int main()
{
  int n;

  printf("Enter an integer\n");
  scanf("%d", &n);
 
  if ((n/2)*2 == n)
    printf("Even\n");
  else
    printf("Odd\n");

  return 0;
}

In C programming language, when we divide two integers, we get an integer result, for example, 7/3 = 2. We can use it to find whether a number is odd or even.

Even numbers are of the form 2*n, and odd numbers are of the form (2*n+1) where n is is an integer.

We can divide an integer by two and then multiply it by two. If the result is the same as the original number, then the number is even otherwise odd.

For example, 11/2 = 5, 5*2 = 10 (which isn't equal to eleven), now consider 12/2 = 6 and 6*2 = 12 (same as the original number). You can use this logic to determine if a number is odd or even.

Even odd program in C using conditional operator

#include <stdio.h>

int main()
{
  int n;

  printf("Input an integer\n");
  scanf("%d", &n);

  n%2 == 0 ? printf("Even\n") : printf("Odd\n");

  return 0;
}