Control Structuresο
This documentation covers the core control structures in C, including conditionals, loops, and the goto statement. These constructs control the flow of execution in a program.
Conditional Statementsο
if Statementο
Executes a block of code only if the condition is true.
int x = 10;
if (x > 5) {
printf("x is greater than 5\n");
}
if-else Statementο
Adds an alternate block if the condition is false.
if (x > 5) {
printf("x > 5\n");
} else {
printf("x <= 5\n");
}
else-if Ladderο
Checks multiple conditions in sequence.
if (x > 10) {
printf("x > 10\n");
} else if (x == 10) {
printf("x == 10\n");
} else {
printf("x < 10\n");
}
switch Statementο
Allows multiple execution paths based on the value of a variable.
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
default:
printf("Another day\n");
}
Loopsο
Loops execute a block of code repeatedly.
while Loopο
Executes as long as the condition is true.
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
do-while Loopο
Executes the body at least once, then checks the condition.
int i = 0;
do {
printf("%d\n", i);
i++;
} while (i < 5);
for Loopο
Compact loop syntax using initialization, condition, and increment.
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
Loop Control: break and continueο
break Statementο
Exits the loop immediately.
for (int i = 0; i < 10; i++) {
if (i == 5) break;
printf("%d\n", i);
}
continue Statementο
Skips the current iteration and continues with the next.
for (int i = 0; i < 5; i++) {
if (i == 2) continue;
printf("%d\n", i);
}
goto Statementο
The goto statement allows jumping to a labeled part of the program. Itβs rarely used and can make code harder to follow, but itβs useful in certain low-level or cleanup scenarios.
Syntaxο
goto label;
// ... other code
label:
// code to jump to
Exampleο
#include <stdio.h>
int main() {
int x = 1;
if (x == 1)
goto skip;
printf("This line is skipped\n");
skip:
printf("Jumped to label\n");
return 0;
}
Warning
Use goto sparingly. Overuse can make code difficult to read and debug. Prefer structured control flow (loops, functions) when possible.