Today lets write a C program to check whether a user entered integer number is EVEN or ODD, without using modular division(%) operator.
Related Read:
Even or Odd Number: C Program (using Modular Division Operator)
Basic Arithmetic Operations In C
Relational Operators In C
An even number is an integer that is exactly divisible by 2. An odd number is an integer that is not exactly divisible by 2.
Note:
1. Even numbers are of the form 2 * n;
2. Odd numbers are of the form (2 * n + 1);
You can substitute n value in above forms and check the resulting numbers for even or odd.
Even or Odd Number: Source Code
#include < stdio.h > int main() { int n; printf("Enter an integer number\n"); scanf("%d", &n); if( (n/2)*2 == n ) { printf("%d is even number\n", n); } else { printf("%d is odd number\n", n); } return 0; }
Output 1
Enter an integer number
2
2 is even number
Output 2
Enter an integer number
3
3 is odd number
Output 3
Enter an integer number
7
7 is odd number
Output 4
Enter an integer number
12
12 is even number
C Program To Check Even or Odd Number, without using Modular Division Operator
[youtube https://www.youtube.com/watch?v=qc-wK_amMzs]
Note: Division of an integer number by 2(which is also an integer number) always returns integer number.
In above c program, we ask the user to input an integer value and store it in variable n. Next using if else condition, we check if the user entered number is even or odd.
User entered integer number is divided by 2. And then it is multiplied by 2. If the final result is equal to the original user entered value, then the user entered value is even orelse its odd.
Example 1:
If user enters n = 2;
Applying n = 2 to ( (n/2)*2 == n ).
( (2/2)*2 == 2 )
( (1)*2 == 2 )
( 2 == 2 ) // true
So user entered value, that is, 2 is even number.
Example 2:
If user enters n = 3;
Applying n = 3 to ( (n/2)*2 == n ).
( (3/2)*2 == 3 )
( (1)*2 == 3 )
( 2 == 3 ) // false
2 is not equal to 3. So user entered value, that is, 3 is odd number.
In above example, 3/2 gives back 1 and not 1.5 as 3 is divided by integer which returns only the integer part and discards the decimal part.
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert