Home >Backend Development >C++ >C program to print 'even' or 'odd' without using conditional statements

C program to print 'even' or 'odd' without using conditional statements

王林
王林forward
2023-09-15 21:21:03566browse

C program to print even or odd without using conditional statements

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.

Method 1

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.

Sample 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
}

The Chinese translation of Output 1

is:

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. 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.

Sample 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.
}

The Chinese translation of Output 1

is:

Output 1

Enter a number: 40
even

Output 2

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete