🔍 Check Even or Odd Using Modulus Operator in C++

Check Even or Odd Using Modulus Operator in C++

🔍 Check Even or Odd Using Modulus Operator in C++

In C++, checking whether a number is even or odd is a basic operation often used in conditional logic, loops, and algorithms. One of the most straightforward methods to perform this check is by using the modulus operator (%). This operator returns the remainder after division of one number by another.

💡 How the Modulus Operator Works

The modulus operator in C++ is written as %. When you divide a number by 2:

  • If the remainder is 0 → the number is even
  • If the remainder is 1 → the number is odd

📄 C++ Code Example


#include <iostream>
using namespace std;

int main() {
    int number;

    // Input from user
    cout << "Enter an integer: ";
    cin >> number;

    // Check if the number is even or odd using modulus
    if (number % 2 == 0) {
        cout << number << " is even." << endl;
    } else {
        cout << number << " is odd." << endl;
    }

    return 0;
}
    

✅ Sample Output

Enter an integer: 7  
7 is odd.
  
Enter an integer: 10  
10 is even.
  

📘 Definition: Even or Odd Check Using Modulus

Checking even or odd using the modulus operator is a method in programming where the remainder of a number divided by 2 determines its parity. If number % 2 equals 0, the number is even; otherwise, it is odd. This is a fast and efficient technique used in many logic-based programs and conditions.

This method is widely supported in most programming languages and is considered the standard way to identify if a number is even or odd. It is helpful in loops, validations, decision-making statements, and algorithm design.

🧠 Final Thoughts

Learning how to check even or odd numbers using the modulus operator is a great start for beginners and helps build logic for more complex programming problems. It's a must-know trick that can be applied in real-world problem-solving and competitive coding.

Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences