In C, an Odd or Even program determines whether a given integer is odd or even by checking the remainder when the number is divided by 2. If the remainder is zero, the number is even; otherwise, it is odd.
Steps for the Odd or Even Program:
- Include Header Files: Include the
stdio.h
library for input/output functions. - Declare Variables: Use a variable to store the number that will be input by the user.
- Take Input: Ask the user to enter an integer.
- Check the Number: Use the modulus operator (
%
) to check if the number is divisible by 2. - Display Output: Print whether the number is odd or even.
Program:
Explanation:
Variables:
int num
: This variable stores the integer entered by the user.
Input:
printf("Enter an integer: ");
prompts the user to enter a number.scanf("%d", &num);
reads the input number from the user and stores it in the variablenum
.
Checking Odd or Even:
- The condition
if (num % 2 == 0)
checks whether the remainder is0
when the number is divided by 2 using the modulus operator (%
).- If
num % 2 == 0
, the number is even, and it prints the messagenum is even
. - If
num % 2 != 0
, the number is odd, and it prints the messagenum is odd
.
- If
- The condition
Output:
- Depending on the input and the condition, the program will display whether the number is even or odd.
Sample Output:
Example 1:
Example 2:
Key Points:
- The modulus operator (
%
) is crucial for checking divisibility. If the remainder is zero when dividing by 2, the number is even; otherwise, it's odd. %d
is the format specifier used to read and print integers.- Conditions: The
if-else
structure helps determine the result based on the input number.
This program provides a simple way to classify numbers as odd or even using basic input/output and conditional logic in C.