Control Structures in C

Learn in Details

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.

1. if Statement

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.");
}

2. if-else Statement

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");
}

3. if-else if-else Ladder

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");
}

4. Nested if

An if statement inside another if statement.

int age = 20;
int hasID = 1;
if (age >= 18) {
  if (hasID) {
    printf("Allowed to enter");
  }
}

5. switch Statement

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.