Check if a Number is Even or Odd

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.

Step-by-Step Objective

  • Declare an int variable to store the user's input.
  • Prompt the user to enter an integer.
  • Apply the condition (num % 2 == 0) within an if statement.
  • Display "Even" if the condition is met, and "Odd" using an else block.

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
Conditional Branching Modulo Arithmetic Relational Operators Parity Algorithms Boolean Evaluation Beginner Logic Exercises

Share this C++ Exercise

Help others learn conditional statements in C++.

© C++ Programming Exercises. Master the art of performance coding.