WAP to check a given number is even or odd
Objective
Write a C++ program to check if a given number is even or odd.
Algorithm / Approach
- Read an integer
a. - Use the modulo operator:
if (a % 2 == 0). - If true, the number is Even.
- Otherwise, the number is Odd.
main.cpp
#include<iostream>
using namespace std;
int main() {
int a;
cout<<"Enter Value for A: ";
cin>>a;
if(a%2==0)
cout<< a<<" IS EVEN NO.\n";
else
cout<< a<<" IS ODD NO.\n";
return 0;
}
Expected Output
Enter Value for A: 12 12 IS EVEN NO.
Explanation of the Program
- The Modulo operator (
%) calculates the remainder of division. - Because every even number is perfectly divisible by 2, dividing an even number by 2 will always result in a remainder of exactly 0. This makes
number % 2 == 0the universal test for even numbers.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)