Compound Conditions
In this tutorial, we will understand what compound conditions are and how they are useful to us.
In this tutorial, we will understand what compound conditions are and how they are useful to us.
Compound conditions are those conditions which are formed by combining multiple conditions using logical operators. They are useful when you want to execute a block of code only after checking a couple of conditions.
For example, you may want to print “Hello User” only when the number provided by the user is either between 10 and 20 (both inclusive) or greater than 50. The program in this case looks like the following:
#include <stdio.h>
int main() {
int number;
// Prompt the user to enter the number
printf("Enter the number: ");
scanf("%d", &number);
// Check if the number is between 10 and 20 (both inclusive) or greater than 50
if ((number >= 10 && number <= 20) || number > 50)
printf("Hello User!");
return 0;
}
The output “Hello User!” is displayed when the number entered by the user is either 10 and 20 or greater than 50. Consider the following prompts and the respective outputs:
Output 1:
Enter the number: 10
Hello User!
Output 2:
Enter the number: 30
The compound statements are very useful when multiple conditions are involved to make the decision. Let’s consider a real-life example to demonstrate this fact.
Let’s say you have been asked to write a program to determine whether a person is eligible to apply for the driver’s license. For this, the following conditions must be satisfied:
Without satisfying the above two conditions, the person is not eligible to apply for the license to drive a vehicle. Since there are two conditions, we can use logical operators to combine them into a compound condition. If the compound condition is satisfied, then the person is eligible to apply, otherwise not. Here is the program to illustrate the same.
#include <stdio.h>
int main() {
int age;
char hasLearnersPermit;
printf("Enter your age: ");
scanf("%d", &age);
printf("Do you have the valid learner's permit? (y/n): ");
scanf(" %c", &hasLearnersPermit);
if (age >= 18 && (hasLearnersPermit == 'y' || hasLearnersPermit == 'Y'))
printf("You are eligible to apply for the driving license.");
else
printf("Sorry! You are not eligible to apply for the driving license.");
return 0;
}
Output:
You can check different values on your own and verify whether the program is working according to your expectations.
Leave a comment