Odd or Even Number Checker in C
This program determines if a given number is odd or even. Below is the C code for the program along with a detailed explanation of its structure and documentation.
Program Code
#include <stdio.h>
/**
* Function to check if a number is odd or even.
* @param number - the number to be checked
* @return 1 if the number is odd, 0 if the number is even
*/
int isOddOrEven(int number) {
return number % 2;
}
int main() {
int number;
// Prompt the user to enter a number
printf("Enter a number: ");
scanf("%d", &number);
// Check if the number is odd or even
if (isOddOrEven(number)) {
printf("The number %d is odd.\n", number);
} else {
printf("The number %d is even.\n", number);
}
return 0;
}
Explanation
Here’s a step-by-step explanation of the program structure:
- Include Header File:
#include <stdio.h>This header file is included to use the standard input-output functions like
printfandscanf. - Function Definition:
/** * Function to check if a number is odd or even. * @param number - the number to be checked * @return 1 if the number is odd, 0 if the number is even */ int isOddOrEven(int number) { return number % 2; }The
isOddOrEvenfunction takes an integer as input and returns1if the number is odd, and0if the number is even. It uses the modulus operator (%) to determine the remainder when the number is divided by 2. - Main Function:
int main() { int number; // Prompt the user to enter a number printf("Enter a number: "); scanf("%d", &number); // Check if the number is odd or even if (isOddOrEven(number)) { printf("The number %d is odd.\n", number); } else { printf("The number %d is even.\n", number); } return 0; }The
mainfunction is the entry point of the program.- It declares an integer variable
number. - It prompts the user to enter a number using
printfand reads the input usingscanf. - It calls the
isOddOrEvenfunction to check if the number is odd or even and prints the result accordingly. - It returns
0to indicate that the program ended successfully.
- It declares an integer variable
