Conditional operator programming exercises
C program to check even or odd number using conditional operator
Write a C program to input a number and check whether number is even or odd using Conditional/Ternary operator ?:. How to check even or odd numbers using conditional operator in C program.
Required knowledge
Operators, Data Types in c, Variables in C, Basic input/output
Program to check even or odd
/** * C program to check even or odd number using conditional operator */ #include <stdio.h> int main() { int num; /* Input a number from user */ printf("Enter any number to check even or odd: "); scanf("%d", &num); /* * If n%2==0 then * print it is even * else * print it is odd */ (num%2 == 0) ? printf("The number is EVEN") : printf("The number is ODD"); return 0; }
Another approach of writing the same program as.
/** * C program to check even or odd number using conditional operator */ #include <stdio.h> int main() { int num; /* Input number from user */ printf("Enter any number to check even or odd: "); scanf("%d", &num); /* Print Even if (num%2==0) */ printf("The number is %s", (num%2==0 ? "EVEN" : "ODD")); return 0; }
Output:
Enter any number to check even or odd: 20 The number is EVEN