Introduction
In C++, determining if a given number is odd or even is a basic but important operation. This is often one of the first programs you write when learning a new programming language. An even number is divisible by 2 with no remainder, while an odd number leaves a remainder of 1 when divided by 2.
The objective of this program is to write a simple C++ program that takes an integer as input from the user and determines whether the number is odd or even using basic conditional statements.
Objective
The objective of this task is to implement a C++ program that:
- Accepts an integer input from the user.
- Uses the modulus operator to check if the number is divisible by 2.
- Prints “Even” if the number is divisible by 2 and “Odd” if it is not.
Code Implementation
#include using namespace std; int main() { int number; // Ask the user for input cout << "Enter an integer: "; cin >> number; // Check if the number is even or odd using modulus operator if (number % 2 == 0) { cout << "The number " << number << " is Even." << endl; } else { cout << "The number " << number << " is Odd." << endl; } return 0; }
Explanation of the Program
Let’s break down the code and understand how it works:
- Include the header file:
#include <iostream>
is used to include the standard input-output stream, which allows us to usecin
for input andcout
for output. - Define the main function:
Themain()
function is the entry point of any C++ program. It is where the program starts executing. - Declare a variable:
int number;
declares an integer variable to store the number input by the user. - Get input from the user:
cin >> number;
prompts the user to input an integer, which is then stored in the variablenumber
. - Check for even or odd:
Theif (number % 2 == 0)
condition uses the modulus operator to check if the remainder when dividingnumber
by 2 is zero (i.e., if the number is divisible by 2). If the condition is true, the number is even; otherwise, it’s odd. - Output the result:
cout << "The number " << number << " is Even." << endl;
displays whether the number is even or odd. - Return 0: The
return 0;
statement marks the successful completion of the program.
How to Run the Program
Follow these steps to run the program:
- Write the code in a C++ editor or an Integrated Development Environment (IDE) like Code::Blocks, Visual Studio, or CLion.
- Save the file with a
.cpp
extension, for example,OddEven.cpp
. - Compile the program. If you’re using a command-line compiler like
g++
, you can compile the code with:g++ OddEven.cpp -o OddEven
- Run the compiled program by typing:
./OddEven
- Enter a number when prompted, and the program will tell you whether it is odd or even.
Conclusion
This program demonstrates how to use basic conditional statements and the modulus operator to determine whether a number is odd or even. It serves as a foundation for learning more complex operations and algorithms in C++ programming.