Control structures allow you to control the flow of a program. They help your program make decisions and execute blocks of code based on conditions.
The if statement executes a block of code if a specified condition is true.
int age = 18;
if (age >= 18) {
printf("You are an adult.");
}
Executes one block if the condition is true, and another block if it is false.
int age = 16;
if (age >= 18) {
printf("Adult");
} else {
printf("Not an adult");
}
Allows checking multiple conditions one after another.
int marks = 75;
if (marks >= 90) {
printf("Grade A");
} else if (marks >= 75) {
printf("Grade B");
} else {
printf("Grade C");
}
An if statement inside another if statement.
int age = 20;
int hasID = 1;
if (age >= 18) {
if (hasID) {
printf("Allowed to enter");
}
}
The switch statement is used to execute one block of code based on the value of a variable.
int day = 3;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
default:
printf("Invalid day");
}
Note: Always use break; after each case to stop fall-through.