Control Structures in C
Control structures in C allow you to control the flow of your program. They include conditional statements (if-else, switch) and loops (for, while, do-while).
If-Else Statements
The if-else
statement is used to execute a block of code based on a condition.
You can also use else if
to check multiple conditions.
#include <stdio.h>
int main() {
int age = 20;
if (age >= 18) {
printf("You are an adult.\n");
} else if (age >= 13) {
printf("You are a teenager.\n");
} else {
printf("You are a child.\n");
}
return 0;
}
Nested If-Else
You can nest if-else
statements to check conditions within conditions.
#include <stdio.h>
int main() {
int age = 20;
char gender = 'M';
if (age >= 18) {
if (gender == 'M') {
printf("You are an adult male.\n");
} else {
printf("You are an adult female.\n");
}
} else {
printf("You are a minor.\n");
}
return 0;
}
Switch Statement
The switch
statement is used to execute one of many code blocks based on the value of an expression.
It is often used as an alternative to multiple if-else
statements.
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}
Loops
Loops are used to execute a block of code repeatedly. C supports for
, while
, and do-while
loops.
For Loop
The for
loop is used when you know how many times you want to execute a block of code.
#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
return 0;
}
While Loop
The while
loop is used when you want to repeat a block of code as long as a condition is true.
#include <stdio.h>
int main() {
int count = 0;
while (count < 5) {
printf("%d\n", count);
count++;
}
return 0;
}
Do-While Loop
The do-while
loop is similar to the while
loop, but it guarantees that the block of code is executed at least once.
#include <stdio.h>
int main() {
int count = 0;
do {
printf("%d\n", count);
count++;
} while (count < 5);
return 0;
}
Break and Continue
The break
statement is used to exit a loop or a switch
statement prematurely.
The continue
statement is used to skip the rest of the loop and proceed to the next iteration.
#include <stdio.h>
int main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d\n", i);
}
return 0;
}
Nested Loops
You can nest loops within loops to create more complex control structures.
#include <stdio.h>
int main() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("i = %d, j = %d\n", i, j);
}
}
return 0;
}
Next: Functions