Compound and Grouping Conditions
Sometimes a decision depends on more than one requirement. Instead of writing several separate if statements, you can combine conditions using logical operators:
&&(AND) – both conditions must betrue;||(OR) – at least one condition must betrue;!(NOT) – reverses the result.
Compound conditions help keep your logic compact and expressive.
main.c
1234567891011121314#include <stdio.h> int main() { int age = 20; int hasID = 1; // Means `true` if (age >= 18 && hasID) { printf("Access granted.\n"); } else { printf("Access denied.\n"); } return 0; }
Here both conditions must be satisfied for access to be allowed.
When compound conditions become long, grouping them with parentheses makes the logic easier to read and prevents mistakes in operator precedence.
main.c
123if ((score > 80 && passedExam) || isAdmin) { printf("Approved.\n"); }
Breaking it down into two parts:
(score > 80 && passedExam);|| isAdmin.
Either the student qualifies, or an admin overrides. Grouping shows the intention clearly.
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Can you give an example of how to use these logical operators in code?
What happens if I don't use parentheses in a complex condition?
Can you explain operator precedence with logical operators?
Fantastiskt!
Completion betyg förbättrat till 9.09
Compound and Grouping Conditions
Svep för att visa menyn
Sometimes a decision depends on more than one requirement. Instead of writing several separate if statements, you can combine conditions using logical operators:
&&(AND) – both conditions must betrue;||(OR) – at least one condition must betrue;!(NOT) – reverses the result.
Compound conditions help keep your logic compact and expressive.
main.c
1234567891011121314#include <stdio.h> int main() { int age = 20; int hasID = 1; // Means `true` if (age >= 18 && hasID) { printf("Access granted.\n"); } else { printf("Access denied.\n"); } return 0; }
Here both conditions must be satisfied for access to be allowed.
When compound conditions become long, grouping them with parentheses makes the logic easier to read and prevents mistakes in operator precedence.
main.c
123if ((score > 80 && passedExam) || isAdmin) { printf("Approved.\n"); }
Breaking it down into two parts:
(score > 80 && passedExam);|| isAdmin.
Either the student qualifies, or an admin overrides. Grouping shows the intention clearly.
Tack för dina kommentarer!