In this section we will see how to check whether a number is odd or even without using any kind of conditional statements like (<, <=, !=, >, >=, ==).
We can easily check the odd or even by using the conditional statements. We can divide the number by 2, then check whether the remainder is 0 or not. if 0, then it is even. Otherwise we can perform AND operation with the number and 1. If the answer is 0, then it is even, otherwise odd.
Here no conditional statements can be used. We will see two different methods to check the odd or even.
Method 1
Here we will create an array of strings. The index 0 position will hold “Even”, and index 1 position will hold “Odd”. We can send the remainder after dividing the number by 2 as index to get the result directly.
Example Code
#include<stdio.h> main() { int n; char* arr[2] = {"Even", "Odd"}; printf("Enter a number: "); //take the number from the user scanf("%d", &n); printf("The number is: %s", arr[n%2]); //get the remainder to choose the string }
Output 1
Enter a number: 40 The number is: Even
Output 2
Enter a number: 89 The number is: Odd
Method 2
This is the second method. In this method we will use some tricks. Here logical and bitwise operators are used. At first we are performing AND operation with the number and 1. Then using logical and to print the odd or even. When the result of bitwise AND is 1, then only the logical AND operation will return the odd result, otherwise it will return even.
Example Code
#include<stdio.h> main() { int n; char *arr[2] = {"Even", "Odd"}; printf("Enter a number: "); //take the number from the user scanf("%d", &n); (n & 1 && printf("odd"))|| printf("even"); //n & 1 will be 1 when 1 is present at LSb, so it is odd. }
Output 1
Enter a number: 40 even
Output 2
Enter a number: 89 odd