Loops
loops in C. In C programming, loops are used to execute a block of code repeatedly as long as a specified condition is true. There are three main types of loops in C: for
, while
, and do-while
. Each type of loop has its own use cases and syntax.
VIDEO CREDIT:-APNA COLLEGE
1. for
Loop
The for
loop is commonly used when the number of iterations is known before entering the loop. Its syntax includes initialization, condition, and increment/decrement expressions.
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Example:
int main() {
for (int i = 0; i < 10; i++) {
printf("Iteration %d\n", i);
}
return 0;
}
In this example, i
is initialized to 0, the loop runs while i
is less than 10, and i
is incremented by 1 after each iteration.
2. while
Loop
The while
loop is used when the number of iterations is not known and depends on a condition. The condition is checked before entering the loop.
Syntax:
while (condition) {
// code to be executed
}
Example:
int main() {
int i = 0;
while (i < 10)
{
printf("Iteration %d\n", i);
i++;
}
return 0;
}
In this example, the loop runs as long as i
is less than 10. The value of i
is incremented within the loop.
3. do-while
Loop
The do-while
loop is similar to the while
loop, but the condition is checked after the code block is executed. This guarantees that the loop will execute at least once.
Syntax:
do {
// code to be executed
} while (condition);
Example:
int main() {
int i = 0;
do {
printf("Iteration %d\n", i);
i++;
}
while (i < 10);
return 0;
}
In this example, the loop executes the block of code and then checks if i
is less than 10.
Nested Loops
Loops can also be nested, meaning you can have one loop inside another. This is useful for working with multi-dimensional arrays and more complex iterative tasks.
Example:
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;
}
In this example, the inner loop runs completely for each iteration of the outer loop.
Break and Continue
break
statement: Exits the loop immediately.continue
statement: Skips the rest of the code inside the loop for the current iteration and proceeds with the next iteration.
Break Example:
int main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
printf("Iteration %d\n", i);
}
return 0;
}
In this example, the loop will stop when i
is equal to 5.
Continue Example:
int main() {
for (int i = 0; i < 10; i++) {
if (i == 5)
{
continue;
}
printf("Iteration %d\n", i);
}
return 0;
}
In this example, when i
is equal to 5, the continue
statement skips the print statement and the loop proceeds with the next iteration.
Understanding these loops and how to use them effectively is fundamental to controlling the flow of your programs in C.
IMAGE SOURCE:-DATACAMP
0 Comments