Check Odd or Even Number in C
Check Whether a Number is Odd or Even in C
This C program determines if a given number is odd or even. Below is the code:
#include <stdio.h>
int main() {
int num;
// Input the number
printf("Enter an integer: ");
scanf("%d", &num);
// Check if the number is odd or even
if (num % 2 == 0) {
printf("%d is even.\n", num);
} else {
printf("%d is odd.\n", num);
}
return 0;
}
Explanation
The program starts by including the <stdio.h>
header file to use input and output functions.
In the main
function, an integer variable num
is declared.
The program prompts the user to enter an integer and reads this value using scanf
.
It then uses the modulus operator %
to determine whether the number is odd or even:
- If
num % 2 == 0
, the number is divisible by 2 without a remainder, so it is even. - If
num % 2 != 0
, there is a remainder, so the number is odd.
The result is then displayed using printf
.
Comments
Post a Comment