In this section, we will see how to use conditional statements without using any conditional statements (such as , >=, ==) In the case of checking whether a number is odd or even.
We can easily check if the number is odd or even by using conditional statement. We can divide the number by 2 and check if the remainder is 0. If 0, it is an even number. Otherwise, we can AND the number with 1. If the answer is 0, it is an even number, otherwise it is an odd number.
Conditional statements cannot be used here. We'll see two different ways to check whether an odd or even number is present.
Here, we will create an array of strings. The index 0 position will hold "even" and the index 1 position will hold "odd". We can get the result directly by taking the remainder after dividing the number by 2 as an index.
#includemain() { 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 }
Enter a number: 40 The number is: Even
Enter a number: 89 The number is: Odd
This is the second method. In this method we will use some tricks. Logical and bitwise operators are used here. First, we AND the number and 1. Then use logical sum to print odd or even numbers. The logical AND operation returns an odd result when the result of the bitwise AND is 1, otherwise it returns an even number.
#includemain() { 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. }
Enter a number: 40 even
Enter a number: 89 odd
The above is the detailed content of C program to print 'even' or 'odd' without using conditional statements. For more information, please follow other related articles on the PHP Chinese website!