Conditional control in C language allows programs to execute different blocks of code based on various conditions. The main conditional control statements are:if statement, if-else statement, if-else if-else statement, switch statement, and the ternary operator (?:)..
1. if statement
#include <stdio.h>
int main(int argc, char *argv[]) { int age = 20; if (age >= 18) { // Develop the habit of using {} even for a single line printf("Adult\n"); }
return 0;}
2. if – else statement
#include <stdio.h>
int main(int argc, char *argv[]) { int age = 16; if (age >= 18) { printf("Adult\n"); } else { printf("Minor\n"); }
return 0;}
3. if – else if – else statement
#include <stdio.h>
int main(int argc, char *argv[]) { int age = 12;
// Condition checking starts from the first if; if the condition is met, // the subsequent ones will not be executed. if (age > 6) { printf("Age is greater than 6\n"); } else if (age <=18) { // This condition will not execute even if met // Because age > 6 has already been satisfied. printf("Age is less than 18\n"); } else { printf("Other ages\n"); }
Execution result:
Age is greater than 6
4. switch statementSimilar to if statements, but more concise.
- Each case usually requires abreak
- The default branch is optional
- Case must be an integer constant expression
#include <stdio.h>
int main(int argc, char *argv[]) { int day = 3; switch (day) { case 1: // Must be an integer constant printf("Monday\n"); break; case 2: printf("Tuesday\n"); break; case 3: printf("Wednesday\n"); // For example, if break is forgotten here, it means that after case 3 ends, it will also go to case 4 // Equivalent to if ( case 3 or case 4) case 4: printf("Thursday\n"); break; case 5: printf("Friday\n"); break; case 6: printf("Saturday\n"); break; case 7: printf("Sunday\n"); break; // Handling for cases not met before default, as needed, is not mandatory. default: printf("Invalid day\n"); } return 0;}
Output result:
Wednesday
Thursday
5. Ternary operator (?:) This is a simplified expression of the if-else statement.
#include <stdio.h>
int main(int argc, char *argv[]) { // Develop the habit of initializing values when defining variables int a = 10; int b = 20; int max = 0;
/* Using the ternary operator Equivalent to if (a > b) { max = a; } else { max = b; } */ max = (a > b) ? a : b; printf("The larger number is: %d\n", max); return 0;}
Output result:
The larger number is: 20
The if statement can be combined with logical operators (&& || !) for multiple conditions.Logical operatorsReference:C Language Operators