Determining Even and Odd Numbers in C++
Introduction
One of the basic tasks in programming is determining whether a given number is even or odd. This simple yet fundamental problem helps beginners understand conditional statements and the modulo operator. In this blog post, we will write a C++ program to determine if a number is even or odd.
The Concept
A number is even if it is divisible by 2 without a remainder. Conversely, a number is odd if it is not divisible by 2, which means there will be a remainder of 1. The modulo operator (%) is used to find the remainder of a division operation. If the remainder when dividing by 2 is zero (num % 2 == 0), the number is even; otherwise, it is odd.
The Code
Let's dive into the code. Below is a simple C++ program to determine if a number entered by the user is even or odd.
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
string result = (num % 2 == 0) ? "Even" : "Odd";
cout << "The number " << num << " is " << result << "." << endl;
return 0;
}
Explanation
Header Inclusion: We include the iostream library, which allows us to use input and output streams.
#include <iostream>Namespace Declaration: We use the standard namespace to avoid prefixing
std::before every standard library usage.using namespace std;Main Function: The entry point of our C++ program is the
mainfunction.int main() {Variable Declaration: We declare an integer variable
numto store the user's input.int num;User Prompt: We prompt the user to enter a number.
cout << "Enter a number: ";Input Handling: We read the input from the user and store it in the
numvariable.cin >> num;Even/Odd Check: We use the ternary operator to check if the number is even or odd. If
num % 2equals 0,resultis assigned "Even"; otherwise, it is assigned "Odd".string result = (num % 2 == 0) ? "Even" : "Odd";Output Result: We print the result to the console.
cout << "The number " << num << " is " << result << "." << endl;End of Program: The program ends with a return statement.
return 0;
Conclusion
This simple program demonstrates the use of basic input/output operations, the modulo operator, and the ternary conditional operator in C++. By understanding and practicing these fundamental concepts, beginners can build a solid foundation in C++ programming. This small exercise is a stepping stone towards more complex programs and applications.
Happy coding!



