Loop in C
Fri, 08 Nov 2024
Before going to the key example, have a look at the picture below:
What do you understand from this picture?
for
loop,while
loop,do-while
loopA for
loop repeats a block of code a specific number of times based on the condition.
Syntax:
for (initialization; condition_check; update_state) {
// body
}
Initialization:
int i = 0;
would initialize i
to start counting from 0
.Condition Check:
i < 10
would keep the loop going as long as i
is less than 10.Update State:
i++
increases i
by 1 after each loop cycle, moving it closer to the condition where the loop will end.Body:
Initialization > Condition Check > Body > Update State > Condition Check > Body > Update State > ...
Have a look at this example.
for (int i = 1; i <= 5; i++) {
printf("Hello World\n");
}
5
times, which means it will print "Hello World" 5 times in 5 lines.Hello World
Hello World
Hello World
Hello World
Hello World
A while
is similar to for
loop.
Only difference is initialization is done before loop, and increment is done usually at the end of body section.
If the condition is true, the loop continues; once it becomes false, the loop stops.
Syntax:
Initialization
while (Condition Check) {
Body
Update State
}
Example:
// Initialization
int i = 2;
while (i < 5) { // Condition Check
// Body
printf("Hello World\n");
// Update State
i++;
}
(4-2+1)=3
times, which means it will print "Hello World" 3 times in 3 lines.Hello World
Hello World
Hello World
A do-while
loop is similar to a while
loop, but with one key difference: it guarantees the execution of the body section at least once regardless of the condition.
In a do-while
loop, the code inside the body section is executed first, and then the condition is checked.
If the condition is true, the loop continues; otherwise stops.
Syntax:
Initialization;
do {
Body
Update State
} while (Condition Check);
Example:
int i = 2; // Initialization
do {
// loop body
printf("Hello World\n");
// Update expression
i++;
} while (i < 4); // Test expression
Output:
Hello World
Hello World
break
immediately exits the loop, regardless of the condition.
Useful when we want to stop the loop based on a certain condition within the body.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // exit loop when i is 5
}
printf("%d\n", i);
}
Output:
0
1
2
3
4 //stops when i becomes 5
continue
skips the current iteration and moves directly to the next iteration of the loop.
Useful when we want to bypass certain parts of the loop body under specific conditions.
Example:
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue; // skip iteration when i is 5
}
printf("%d\n", i);
}
0
1
2
3
4 //here 5 is not printed
6
7
8
9
This is a comment 1.
This is a comment 2.