In C programming, it is often necessary to check whether a given number is even or odd. An even number is a number that is divisible by 2 without a remainder, while an odd number is not. This is a simple task, but it can be a useful building block for more complex programs.
Problem Statement:
Write a C program to check whether a given number is even or odd.
Solution:
We can use the modulo operator (%) to determine whether a number is even or odd. An even number will have a remainder of 0 when divided by 2, while an odd number will have a remainder of 1.
Here’s the code for our solution:
#include <stdio.h> int main() { int number; printf("Enter a number: "); scanf("%d", &number); if(number % 2 == 0) { printf("%d is even.", number); } else { printf("%d is odd.", number); } return 0; }
- The
stdio.h
header file is included for standard input/output functions. - The
main()
function is declared as the entry point of the program. - The
number
variable is declared to hold the user input. - The user is prompted to enter a number using
printf()
function. - The user input is read and stored in the
number
variable usingscanf()
function. - An
if-else
statement is used to check whether the number is even or odd. - If the number is even (i.e., the remainder when dividing by 2 is 0), the
printf()
function is called to display a message indicating that the number is even. - If the number is odd (i.e., the remainder when dividing by 2 is 1), the
printf()
function is called to display a message indicating that the number is odd. - The
main()
function returns 0, which indicates that the program has executed successfully.
Output
Explanation:
The program begins by including the stdio.h
header file, which provides access to standard input/output functions. The main()
function is then declared as the entry point of the program, and the number
variable is declared to hold the user input.
Next, the user is prompted to enter a number using the printf()
function. The scanf()
function is then used to read the user input and store it in the number
variable.
An if-else
statement is used to check whether the number is even or odd. If the number is even (i.e., the remainder when dividing by 2 is 0), the printf()
function is called to display a message indicating that the number is even. If the number is odd (i.e., the remainder when dividing by 2 is 1), the printf()
function is called to display a message indicating that the number is odd.
Finally, the main()
function returns 0, indicating that the program has executed successfully.