Logical and Operator in C
0 264
The logical AND operator (&&) in C is used to combine two conditions.
It returns 1 if both conditions are evaluated to be true, otherwise, it returns 0.
It short-circuits, meaning if the left operand is false, the right operand is not evaluated.
Syntax of logical AND operator(&&) in C:
expression1 && expression2
Truth Table:
Expression 1 | Expression 2 | Result |
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
Examples:
Checking if a number is both even and greater than 14:
// program for checking if a number is both even and greater than 14 #include<stdio.h>int main() { int num; printf("Enter a number: "); scanf("%d", &num); if (num % 2 == 0 && num > 14) { printf("The number is even and greater than 14.\n"); } else { printf("The number is not a even no and greater than 14.\n"); } return 0; }
Output:
Enter a number: 3 The number is not a even no and greater than 14.
Checking if a character is both a letter and lowercase:
#include<stdio.h>#include<ctype.h> int main() { char ch; printf("Enter a character: "); scanf("%c", &ch); if (isalpha(ch) && islower(ch)) { printf("The character is a lowercase letter.\n"); } else { printf("The character is not a lowercase letter.\n"); } return 0; }
Output:
Enter a character: hello The character is a lowercase letter.
Verifying if a number is divisible by both 2 and 3 simultaneously.
// program for Verifying if a number is divisible by both 2 and 3 simultaneously. #include<stdio.h>int main() { int num; printf("Enter a number: "); scanf("%d", &num); if (num % 2 == 0 && num % 3 == 0) { printf("Verifying if a number is divisible by both 2 and 3 simultaneously..\n"); } else { printf("The number is not divisible by both 2 and 3.\n"); } return 0; }
Output:
Enter a number: 4 The number is not divisible by both 2 and 3.
Share:
Comments
Waiting for your comments