Introduction to Loops in C
Loops are an essential programming construct that allow you to execute a set of statements repeatedly as long as a certain condition is met. In the C programming language, there are three main types of loops: `for`, `while`, and `do-while`. These loops serve different purposes but all help in controlling the flow of your program.
1. The `for` Loop
The `for` loop in C is a versatile loop that consists of three parts: initialization, condition, and update. It is commonly used when you know the number of iterations in advance.
for (initialization; condition; update) {
// Code to be repeated
}
Example:
for (int i = 1; i <= 5; i++) {
printf("Iteration %d\n", i);
}
2. The `while` Loop
The `while` loop repeatedly executes a block of code as long as a given condition is true. It's useful when you don't know the number of iterations beforehand.
while (condition) {
// Code to be repeated
}
Example:
int num = 1;
while (num <= 5) {
printf("Number: %d\n", num);
num++;
}
3. The `do-while` Loop
Similar to the `while` loop, the `do-while` loop executes a block of code as long as a given condition is true. The main difference is that the condition is checked after the block of code is executed, ensuring the code is executed at least once.
do {
// Code to be repeated
} while (condition);
Example:
int choice;
do {
printf("1. Play\n");
printf("2. Quit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
} while (choice != 2);
Loop Control Statements
1. `break` Statement
The `break` statement is used to exit the current loop prematurely, regardless of whether the loop condition is still true.
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
printf("Iteration %d\n", i);
}
2. `continue` Statement
The `continue` statement is used to skip the rest of the current iteration and move to the next iteration of the loop.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
printf("Iteration %d\n", i);
}
0 Comments