Subscribe

Tag: checkEven or Odd Number

Today I will show How can we check a number is odd or even in C Programming Language. We also use different method to identify even and odd numbers.

As we all know if we divide any number by 2 and the remainder is 0 (zero), then that number is Even, Otherwise its odd. We will use same logic here in C Programming. In C Programming we can get remainder by % (Modulus) operator.

For example of modulus operator, 3%2 gives 1 as remainder. Even numbers are in form of (2*x) and Odd numbers are in form of ((2*x)+1). Here ‘x’ is integer number.

Program 1: Check whether number is even or odd using modulus operator

Check Even or Odd number C Programming Language

C

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

#include<stdio.h>

main()

{

intn;

printf("Enter an integer\n");

scanf("%d",&n);

if(n%2==0)

printf("Even\n");

else

printf("Odd\n");

return0;

}

We can also check the whether the number is even or odd using bitwise operator & (AND).

For example, Binary of 9 is 1001. When we perform 9 & 1, The result will be 1 and you may observe that the least significant bit of every odd number is 1, so ( odd_number & 1 ) will be always one and also ( even_number & 1 ) is zero.

Program 2: Check whether number is even or odd using Bitwise operator

Check whether number is even or odd using bitwise operator in C Programming Language

C

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

#include<stdio.h>

main()

{

intn;

printf("Enter an integer\n");

scanf("%d",&n);

if(n&1==1)

printf("Odd\n");

else

printf("Even\n");

return0;

}

Program 3: Check whether number is even or odd using Conditional Operator (Without using ‘if’ Conditional Operator)

Check whether number is even or odd using Conditional Operator - C Programming Language

C

1

2

3

4

5

6

7

8

9

10

11

12

13

#include<stdio.h>

main()

{

intn;

printf("Input an integer\n");

scanf("%d",&n);

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

return0;

}

In C Programming Language when we divide two integers we get an integer result.

For example the result of 7/3 will be 2. We can take advantage of this and can use it to find whether the number is odd or even. Consider an integer ‘n’ we can first divide by 2 and then multiply it by 2 if the result is the original number then the number is even otherwise the number is odd. For example 11/2 = 5, 5*2 = 10 (which is not equal to eleven), now consider 12/2 = 6 and 6 *2 = 12 ( same as original number). These are some logic which may help you in finding if a number is odd or not.

Program 4: Check whether number is even or odd without using Modulus or Bitwise Operator

Check whether number is even or odd without using Modulus or Bitwise Operator C Programming Language