C Program To Check Whether A Number Is Even Or Odd Using Conditional Operator
Determining whether a number is even or odd is a fundamental concept in programming, often used to introduce conditional logic. In C programming, this check can be performed efficiently using various operators and control structures. In this article, you will learn how to leverage the conditional operator, also known as the ternary operator, to concisely check if a given number is even or odd.
Problem Statement
The core problem is to ascertain if an integer is perfectly divisible by 2. If it is, the number is even; otherwise, it is odd. This seemingly simple check is a building block for many algorithms and data processing tasks, from basic input validation to more complex numerical analyses.
Example
Suppose we input the number 7. The program would output:
7 is an Odd number.
If we input 10, the program would output:
10 is an Even number.
Background & Knowledge Prerequisites
To understand this article, readers should be familiar with:
- Basic C syntax: Understanding how to declare variables, take input, and print output.
- Arithmetic Operators: Specifically, the modulo operator (
%), which returns the remainder of a division. - Conditional Operator (Ternary Operator): Its basic structure and how it evaluates expressions.
For setting up, ensure you have a C compiler (like GCC) installed on your system. No special imports beyond stdio.h are required.
Use Cases or Case Studies
Checking for even or odd numbers is useful in several programming scenarios:
- Data Validation: Ensuring user input meets specific criteria (e.g., only even numbers allowed for a certain operation).
- Algorithm Design: Many algorithms process elements differently based on their parity (even or odd index, even or odd value).
- Game Development: Alternating turns between two players (Player 1 on odd turns, Player 2 on even turns).
- Pattern Generation: Creating patterns or sequences that depend on the evenness or oddness of row/column numbers.
- Basic Mathematical Operations: Foundations for number theory problems or simple calculations.
Solution Approaches
While an if-else statement is commonly used, the conditional operator offers a more compact way to handle simple conditions.
Approach 1: Using if-else Statement
This is the most straightforward and often the first method taught for conditional checks.
- One-line summary: Uses an
ifblock to test a condition and anelseblock for the alternative.
// Even or Odd using if-else
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number % 2 == 0) {
printf("%d is an Even number.\\n", number);
} else {
printf("%d is an Odd number.\\n", number);
}
return 0;
}
- Sample Output:
Enter an integer: 15
15 is an Odd number.
- Stepwise Explanation:
- The program prompts the user to enter an integer.
- It reads the integer into the
numbervariable. - The
if (number % 2 == 0)condition checks if the remainder whennumberis divided by 2 is equal to 0. - If true, the number is even, and the corresponding message is printed.
- If false, the number is odd, and the
elseblock's message is printed.
Approach 2: Using the Conditional Operator
The conditional operator provides a concise way to write if-else constructs when you need to assign a value or execute a simple expression based on a condition.
- One-line summary: Uses the
? :operator to evaluate a condition and return one of two values.
// Even or Odd using Conditional Operator
#include <stdio.h>
int main() {
// Step 1: Declare an integer variable to store the user's number.
int number;
// Step 2: Declare a character pointer to store the result string ("Even" or "Odd").
const char *result_string;
// Step 3: Prompt the user to enter an integer.
printf("Enter an integer: ");
// Step 4: Read the integer from the user.
scanf("%d", &number);
// Step 5: Use the conditional operator to determine if the number is even or odd.
// The condition (number % 2 == 0) is evaluated.
// If true, "Even" is assigned to result_string.
// If false, "Odd" is assigned to result_string.
result_string = (number % 2 == 0) ? "Even" : "Odd";
// Step 6: Print the number and the determined result string.
printf("%d is an %s number.\\n", number, result_string);
return 0;
}
- Sample Output:
Enter an integer: 24
24 is an Even number.
- Stepwise Explanation:
- An integer
numberis declared to hold user input, andresult_string(a pointer to a constant character array) is declared to store either "Even" or "Odd". - The program prompts the user and reads an integer into
number. - The core logic
result_string = (number % 2 == 0) ? "Even" : "Odd";is executed:
-
number % 2 == 0: This is the condition. If the remainder ofnumberdivided by 2 is 0, the condition is true. -
? "Even" : "Odd": If the condition is true, the expression before the colon ("Even") is evaluated and its value is assigned toresult_string. If the condition is false, the expression after the colon ("Odd") is evaluated and assigned.
- Finally,
printfdisplays the original number and the determinedresult_string.
Conclusion
The conditional operator in C provides a compact and efficient way to handle simple if-else scenarios, such as determining if a number is even or odd. While an if-else statement offers more flexibility for complex multi-statement blocks, the conditional operator excels in clarity and brevity for single-expression choices, making the code more readable for straightforward conditions.
Summary
- Even/Odd Definition: A number is even if it's perfectly divisible by 2 (remainder 0); otherwise, it's odd.
- Modulo Operator (
%): Key for checking divisibility;number % 2 == 0for even,number % 2 != 0for odd. - Conditional Operator (
? :): A shorthand forif-elsestatements, structured ascondition ? value_if_true : value_if_false. - Conciseness: Using the conditional operator results in more compact code for simple true/false outcomes compared to a full
if-elseblock.