Today lets write a C program to check whether a user entered integer number is EVEN or ODD, without using modular division(%) operator and by using Ternary Operator / Conditional Operator.
Related Read:
Even or Odd Number without using Modular Division: C Program
Ternary Operator / Conditional Operator In C
Please visit the links I’ve posted above without fail before watching the video posted below.
Even or Odd Number: Source Code
#include < stdio.h > int main() { int n; printf("Enter a integer number\n"); scanf("%d", &n); ( (n/2)*2 == n ) ? (printf("%d is Even\n", n)) : (printf("%d is Odd\n", n)); return 0; }
Output 1:
Enter a integer number
10
10 is Even
Output 2:
Enter a integer number
5
5 is Odd
Even or Odd Number using Ternary Operator and without using Modular Division: C Program
[youtube https://www.youtube.com/watch?v=4-AoNsgYJQ4]
Note: Division of an integer number by 2(which is also an integer number) always returns integer number.
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 list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert