You are here

Even or odd program in C

C program to check odd or even: We will determine whether a number is odd or even by using different methods all are provided with a C language program. As you have studied in Mathematics that in decimal number system even numbers are divisible by two while odd numbers are not so we can use modulus operator(%) which returns remainder, for example, 4%3 gives 1 (remainder when four is divided by three). Even numbers are of the form 2*n, and odd numbers are of the form (2*n+1) where n is is an integer.

Odd or even program in C using modulus operator

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.    int n;
  6.    
  7.    printf("Enter an integer\n");
  8.    scanf("%d", &n);
  9.    
  10.    if (n%2 == 0)
  11.       printf("Even\n");
  12.    else
  13.       printf("Odd\n");
  14.      
  15.    return 0;
  16. }

We can use bitwise AND (&) operator to check odd or even, as an example consider binary of 7 (0111) when we perform 7 & 1 the result will be one, and you may observe that the least significant bit of every odd number is 1. Therefore (odd_number & 1) will be one always and also (even_number & 1) is always zero.

C program to find odd or even using bitwise operator

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.    int n;
  6.    
  7.    printf("Input an integer\n");
  8.    scanf("%d", &n);
  9.    
  10.    if (n & 1 == 1)
  11.       printf("Odd\n");
  12.    else
  13.       printf("Even\n");
  14.      
  15.    return 0;
  16. }

C program to check even or odd using conditional operator

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.    int n;
  6.    
  7.    printf("Input an integer\n");
  8.    scanf("%d", &n);
  9.  
  10.    n%2 == 0 ? printf("Even\n") : printf("Odd\n");
  11.      
  12.    return 0;
  13. }

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

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.    int n;
  6.    
  7.    printf("Enter an integer\n");
  8.    scanf("%d", &n);
  9.    
  10.    if ((n/2)*2 == n)
  11.       printf("Even\n");
  12.    else
  13.       printf("Odd\n");
  14.      
  15.    return 0;
  16. }

In C programming language when we divide two integers we get an integer result, for example, 7/3 = 2. So we can use it to find whether the number is odd or even. Consider an integer 'n' we can first divide it by two and then multiply it by two if the result is same as the original number then the number is even otherwise it is 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 original number). These are some logic which you may use to determine if a number is odd or even.