C++ Program to Check Whether Number is Even or Odd.

Given a number num, write a C++ Program to check whether the given number is Even or Odd

Example:

Input: num = 8
Output: Even

Input: num = 11
Output: Odd

Note: To understand this example, you must know the basics of C++ programming and if..else statements. 

Approach 1: If the given number is divisible by 2 then the number is Even and if the number is not divisible by 2 then the number is Odd.

Pseudo Code:
Step 1: Read a number "num"
Step 2: If "num % 2" is equal to 0, then
    Step 2.1: Print "num is an even number"
Step 3: Else,
    Step 3.1: Print "num is an odd number"
Step 4: End

Following C++ Program to check if a number is Even or Odd:
//C++ Program to check Even or Odd
#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;

    if (num % 2 == 0) {
        cout << num << " is an even number" << endl;
    } else {
        cout << num << " is an odd number" << endl;
    }

    return 0;
}
Output:
Enter a number: 12
12 is an even number

Explanation: 
The program takes an input number and calculates the remainder when it is divided by 2. If the remainder is 0, then the number is even, and if it's not 0, then the number is odd.


Approach 2
In this approach, we use the bitwise "&" operator to check if the least significant bit (LSB) of the number is set. If the LSB is set, then the number is odd, and if it's not set, then the number is even. 

Below is the C++ code Implementation:
//C++ Program to check Odd and Even using Bitwise
#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;

    if (num & 1) {
        cout << num << " is an odd number" << endl;
    } else {
        cout << num << " is an even number" << endl;
    }

    return 0;
}
Output:
Enter a number: 11
11 is an odd number
NoteThis approach is faster than the modulo operator (%), as the bitwise operator is typically faster than the modulo operator. (alert-success)

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS