Check if a Number is Even or Odd in C++
Learn to implement conditional logic in your programs by determining whether an integer is even or odd using the modulo operator.
Logic and Conditionals
The Modulo Operator (%)
This operator returns the remainder of a division. If number % 2 equals 0, the number is even; otherwise, it is odd.
If-Else Structure
Conditional statements allow the program to take different paths based on whether a specific condition is true or false.
Key Concepts Learned:
- Control Flow: Directing execution with
if-elseblocks. - Remainder Logic: Using
%to solve mathematical problems. - Input Validation: Handling integer data from the user.
Course:
Introduction to C++
Step-by-Step Objective
- Declare an
intvariable to store the user's input. - Prompt the user to enter an integer.
- Apply the condition
(num % 2 == 0)within anifstatement. - Display "Even" if the condition is met, and "Odd" using an
elseblock.
C++ Solution
even_odd.cpp
C++ Beginners
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
// Check if the remainder of division by 2 is zero
if (num % 2 == 0) {
cout << num << " is an even number." << endl;
} else {
cout << num << " is an odd number." << endl;
}
return 0;
}
Console Output:
Enter an integer: 7
7 is an odd number.
Decision Making & Modulo Logic