Welcome to our deep dive into C Logical Operators! In this lesson, we'll explore how to combine simple conditions to make more complex ones, using the power of logical operators. Let's get started! 📝
Logical operators allow us to combine multiple conditions in a C program. They help us create more complex and powerful conditions, enabling us to make decisions based on multiple variables or conditions.
There are three logical operators in C:
&& (Logical AND)|| (Logical OR)! (Logical NOT)The && operator checks if both the conditions are true. If both conditions are true, then only the overall condition becomes true.
#include <stdio.h>
int main() {
int a = 10, b = 20;
if (a > 5 && b > 15) {
printf("Both conditions are true.\n");
}
return 0;
}In this example, we have two conditions: a > 5 and b > 15. If both conditions are true, then the overall condition is true, and the message "Both conditions are true." is printed.
Try modifying the values of a and b to understand how the && operator works!
The || operator checks if at least one of the conditions is true. If at least one condition is true, then the overall condition becomes true.
#include <stdio.h>
int main() {
int a = 10, b = 5;
if (a > 5 || b > 15) {
printf("At least one condition is true.\n");
}
return 0;
}In this example, we have two conditions: a > 5 and b > 15. Since a > 5 is true, the overall condition is true, and the message "At least one condition is true." is printed.
Modify the values of a and b to see how the || operator behaves.
The ! operator negates the value of a condition. If the original condition is true, the negated condition is false, and vice versa.
#include <stdio.h>
int main() {
int a = 10;
if (!(a < 5)) {
printf("a is not less than 5.\n");
}
return 0;
}
``In this example, we have the condition a < 5. By using the ! operator, we negate this condition, meaning the overall condition is true if a is not less than 5.
Try changing the value of a to test the ! operator.
Which logical operator checks if both conditions are true?
Write a program that uses logical operators to check if a user is eligible to vote. The conditions are as follows:
Here is a hint:
#include <stdio.h>
int main() {
int age = 17;
char nationality = 'I'; // 'I' for Indian, 'F' for Foreign
// Complete the code to check if the user is eligible to vote
return 0;
}#include <stdio.h>
int main() {
int age = 17;
char nationality = 'I'; // 'I' for Indian, 'F' for Foreign
if (age >= 18 && (nationality == 'I' || (nationality == 'F' && age >= 18 && nationality == 'PR'))){
printf("The user is eligible to vote.\n");
} else {
printf("The user is not eligible to vote.\n");
}
return 0;
}Congratulations! You've mastered C Logical Operators. Keep practicing, and soon you'll be able to create powerful and complex conditions in your C programs. Happy coding! 🎉