#include <stdio.h>
int main()
{
// Declare an integer variable to hold the user input
int number;
// Prompt the user to enter a number
printf("Enter an integer: ");
scanf("%d", &number);
// Check if the number is even or odd
if (number % 2 == 0) {
// If the remainder when divided by 2 is 0, it's even
printf("%d is an even number.\n", number);
} else {
// If the remainder is not 0, it's odd
printf("%d is an odd number.\n", number);
}
return 0; // End of the program
}
Explanation:
- Including the standard input-output library: We include the
stdio.h
header file, which allows us to use functions likeprintf
andscanf
for input and output.cCopy code#include <stdio.h>
- Main Function: Every C program starts execution from the
main()
function. Inside this function, we’ll write our code logic.cCopy codeint main() { ... }
- Declaring a variable: We declare an integer variable
number
to store the number that the user will input.cCopy codeint number;
- User Input: We prompt the user to enter a number using the
printf
function. Then, we usescanf
to capture the input and store it in the variablenumber
.cCopy codeprintf("Enter an integer: "); scanf("%d", &number);
- Checking if the number is even or odd:
- We use the modulus operator (
%
) to check whether the remainder of the number divided by 2 is zero. - If the remainder is
0
, it means the number is even, so the program prints that the number is even. - If the remainder is not
0
, the number is odd, and the program prints that the number is odd.
if (number % 2 == 0) { printf("%d is even.\n", number); } else { printf("%d is odd.\n", number); }
- We use the modulus operator (
- Returning 0: Finally, the program returns
0
to indicate that it executed successfully.cCopy codereturn 0;
OUTPUT
Enter an integer: 8
8 is even.
Summary:
- The
%
operator helps us check if a number is divisible by 2. - The program handles both even and odd numbers by displaying a message accordingly.