Saturday, June 19, 2021
Home coding Write a program to check number is even or odd .

Write a program to check number is even or odd .

Given a number we have to find whether number is even or odd without using mod operator.

So what is even and odd number?

Even Number: number that is divisible by 2.

odd number:number that is not divisble by 2.

Example:

input:28
output:even 

input:37
output:odd

there are two approach to find even and odd number

1-by using mod operator.

2-by using xor operator.

Approach 1:using modulus operator.

#include<iostream>
using namespace std;
int main()
{
int number;
cout<<"enter a number "<<endl;
cin>>number;

if(number%2==0)
{
cout<<"number is even "<<endl;
}
else
{
cout<<"number is odd "<<endl;
}
}
enter a number :69
number is odd.

Approach 2 : by using xor operator.

Logic:

main idea is to check whether the last bit of number is set or not.

#include<iostream>
using namespace std;
bool even(int number)
{
    
    return (!(number&1));
    //if it is true then it is even otherwise it is false
}
int main()
{
int number;
cout<<"enter a number "<<endl;
cin>>number;
if(even(number)==true)
{
cout<<"number is even "<<endl;
}
else
{
cout<<"number is odd "<<endl;
}
}
enter a number :72
number is even 

Time Complexity:O(1)

space complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments