Different ways to find given number is Even or Odd in C
Once upon a day I faced this question in my college day ,"Write a program to find a number is Even or Odd". When I here it is , My mind said this so easy. But I know only a one way to find. So, after that I searched over my search engine for this question. And lastly I find many different and surprising ways..
Here I going to share my knowledge and opinions on finding a given is Even or Odd.
Method one:
Using modulus operator ( A basic way :))
Modulus operator returns the remainder in the division operation. Many people easily check the number is divisible by 2 and this same thing is happening in this method also.
#include <stdio.h>
int main(){
int n;
printf"Enter a number :");
scanf("%d",&n);
if(n%2==0)
printf("Given number is Even");
else
printf("Given number is Odd");
return 0;
}
Method Two:
Using Arithmetic operation ( A basic way :))
This technique looks so easy to understand and we do it in our elementary school levels.
#include <stdio.h>
int main(){
int n;
printf"Enter a number :");
scanf("%d",&n);
if(((n/2)*2)==n)
printf("Given number is Even");
else
printf("Given number is Odd");
return 0;
}
Using Bitwise & operator ( A basic way :))
Somebodies are feel hardness when hearing the words,"Bitwise","Bit manipulation"..
But these techniques are really not hard like they think! It is just a operations of a number system which has the base 2.
#include <stdio.h>
int main(){
int n;
printf"Enter a number :");
scanf("%d",&n);
if(n&1!=1)
printf("Given number is Even");
else
printf("Given number is Odd");
return 0;
}
Note in the binary system odd numbers are always has the 1 in their least significant bit (LSB) and the even is opposite to that.
Using Bitwise shift operators ( A basic way :))
#include <stdio.h>
int main(){
int n;
printf"Enter a number :");
scanf("%d",&n);
if((n>>1)<<1 == n)
printf("Given number is Even");
else
printf("Given number is Odd");
return 0;
}
Comments
Post a Comment
COMMENTS IN TAMIL ARE ALSO WELCOME.