Code Optimization Technique Between Logical AND and Logical OR

Share Your Love

Logical AND(&&) and Logical OR( || ) both are using to handle multiple conditions.

Logical AND ( && ):

While talking about logical AND( && ) if the first condition is false then the compiler doesn’t follow the second condition to check.

#include <iostream.h> 

// Function to check whether n is odd 
bool isOdd(int n); 

// Function to check whether n is prime 
bool isPrime(int n); 

int main() 
{ 
	int cnt = 0, n = 10; 

	// Implementation 1 
	for (int i = 2; i <= n; i++) { 
		if (isOdd(i) && isPrime(i)) 
			cnt++; 
	} 

	cnt = 0; 
	n = 10; 

	// Implementation 2 
	for (int i = 2; i <= n; i++) { 
		if (isPrime(i) && isOdd(i)) 
			cnt++; 
	} 
} 

On above the code Implementation

In first implementation it checks odd number or not before going to check prime. If it satisfy the first condition then it moves to next. Otherwise the first condition false it comes out from the block whereas if the prime number is satisfy condition.

In second implementation it checks the prime number or not before going to check whether it is odd number or not. That is unnecessary computation as all excluding 2 the other numbers are not going to check prime but it goes to check odd number also.

Logical OR (||):

This operator also used multiple condition based. If any one condition true then if block will executed. So the compiler doesn’t need to check the second condition if first condition is true.

#include <iostream.h> 

// Function to check whether n is odd 
bool isEven(int n); 

// Function to check whether n is prime 
bool isPrime(int n); 

int main() 
{ 
	int cnt = 0, n = 10; 

	// Implementation 1 
	for (int i = 3; i <= n; i++) { 
		if (isEven(i) || !isPrime(i)) 
			cnt++; 
	} 
} 

So, in this code the compiler first reach to check the even, if true then it moves to second condition to check not prime. If both true then the statement cnt++ implemented. If the first condition false and then second true the statement cnt++ implemented. Both false not implemented.

The probability of even is more than the prime numbers. For larger inputs the order of execution can affect the overall execution time of the program.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 366

Newsletter Updates

Enter your email address below to subscribe to our newsletter