English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of C Programming Examples
In this example, you will learn to check if the number entered by the user is even or odd.
To understand this example, you should understand the followingC programmingTopic:
Even numbers are those that can be2divisible. For example: 0,8,-24
Odd numbers are those that cannot be2divisible integers. For example:1,7,-11,15
#include <stdio.h> int main() { int num; printf("Enter an integer: "); scanf("%d", &num); //If num is divisible by2divisible then it is true if(num %% 2 == 0) printf("%d is even.", num); else printf("%d is odd.", num); return 0; }
Output Result
Enter an integer: -7 -7 is odd.
In the program, the integer input by the user is stored in the variable num.
Then, use the modulus % operator to check if num is completely divisible by2divisible.
If the number is completely divisible by2divisible, then the test expression #%2 evaluation result of == 0 is1 (true). This means the number is even.
But, if the evaluation result of the test expression is 0 (false), then the number is odd.
#include <stdio.h> int main() { int num; printf("Enter an integer: "); scanf("%d", &num); (num %% 2 == 0) ? printf("%d is even.", num) : printf("%d is odd.", num); return 0; }
Output Result
Enter an integer: 33 33 is odd.
In the above program, we used the ternary operator ?: instead of if...else statements.