Introduction

Control structures in C allow the programmer to control the flow of execution in a program. They are essential for decision-making, looping, and altering the sequence of instructions.

Control structures are broadly classified into three categories:

1. Conditional Control Structures

These structures help in decision-making by executing different code blocks based on certain conditions.

a) if, else if, else

  • Executes a block of code if a condition is true.
  • else if and else handle other conditions. Example:
int temp = 35;
if (temp > 40)
    printf("High temperature\n");
else if (temp > 30)
    printf("Moderate temperature\n");
else
    printf("Low temperature\n");

b) switch

  • Used when a variable is compared against multiple constant values.

  • Helps reduce the complexity of multiple if-else conditions.

Example:

int mode = 2;
switch (mode) {
    case 1: printf("Manual Mode\n"); break;
    case 2: printf("Auto Mode\n"); break;
    default: printf("Unknown Mode\n");
}

2. Looping Control Structures

Loops are used to repeat a set of statements multiple times.

a) for loop

  • Best suited for cases where the number of iterations is known beforehand. Example:
for (int i = 0; i < 5; i++) {
    printf("i = %d\n", i);
}

b) while loop

  • Used when the number of iterations is not known in advance.
  • Condition is checked before entering the loop. Example:
int i = 0;
while (i < 3) {
    printf("i = %d\n", i);
    i++;
}

c) do...while loop

  • Similar to the while loop, but the body is executed at least once. Example:
int i = 0;
do {
    printf("i = %d\n", i);
    i++;
} while (i < 3);

3. Branching (Jump) Statements

These statements are used to alter the normal flow of control in a program.

a) break

  • Immediately exits from a loop or switch statement. Example:
for (int i = 0; i < 5; i++) {
    if (i == 3) break;
    printf("%d ", i);
}

b) continue

  • Skips the current iteration and jumps to the next iteration of the loop. Example:
for (int i = 0; i < 5; i++) {
    if (i == 2) continue;
    printf("%d ", i);
}

c) goto

  • Transfers control to a labeled statement in the program.
  • Generally avoided, but sometimes used in low-level programming or error handling. Example:
int x = 1;
if (x)
    goto end;
 
printf("This will be skipped\n");
 
end:
printf("Reached end label\n");