- How to check whether a number is odd or even without using if else statement in one line.
- Write a program in C to check a number is odd or even.
Algorithm to check odd and even number using bitwise operator
- Check whether least significant bit of a number(N) is 0 or not by doing bitwise And(&) with 1. if (N & 1) == 0, that means N is even otherwise odd number.
C program to check odd or even number using bitwise operator
#include<stdio.h> int main() { int n; printf("Enter a number\n"); scanf("%d", &n); (n & 1 && printf("Odd"))|| printf("Even"); return 0; }Output
Enter a number 3 3 is Odd
Enter a number 12 12 is Even
C program to check odd or even number using bitwise operator
Algorithm to check odd and even number using bitwise operator
- If input number(N) is divisible by 2(N%2 == 0) then N is even otherwise odd number.
#include<stdio.h> int main() { int n; char *strList[] = {"Even", "Odd"}; printf("Enter a number\n"); scanf("%d", &n); printf("%d is %s", n, strList[n%2]); return 0; }Output
Enter a number 5 5 is Odd
Enter a number 8 8 is Even