C loops
Created By: chatGPT
Loops in C allow you to execute a block of code multiple times. There are three primary types of loops: for, while, and do-while. Understanding how to use each type effectively can significantly improve your programming efficiency.
// For loop example
#include <stdio.h>
int main() {
for(int i = 0; i < 10; i++) {
printf("%d\n", i);
}
return 0;
}
The for loop consists of three parts: initialization, condition, and iteration. In the above example, it initializes
i
to 0, checks if i < 10
, and increments i
by 1 after each iteration. This results in printing numbers from 0 to 9.// While loop example
#include <stdio.h>
int main() {
int i = 0;
while(i < 10) {
printf("%d\n", i);
i++;
}
return 0;
}
The while loop checks the condition before executing the block. If the condition is true, it executes the block; otherwise, it exits. In this example, it behaves similarly to the for loop but offers more flexibility in how you manage the loop variable.
// Do-while loop example
#include <stdio.h>
int main() {
int i = 0;
do {
printf("%d\n", i);
i++;
} while(i < 10);
return 0;
}
The do-while loop guarantees at least one execution of the code block, as it evaluates the condition after executing the loop. This is particularly useful when the code should run at least once regardless of the condition.
// Nested loop example
#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;
}
Nested loops are loops within loops. In this example, the outer loop runs three times, and for each iteration of the outer loop, the inner loop also runs three times. This results in a combination of
Control statements like i
and j
values printed consecutively.// Loop control statements example
#include <stdio.h>
int main() {
for(int i = 0; i < 5; i++) {
if(i == 2) {
continue; // Skip the iteration when i is 2
}
if(i == 4) {
break; // Exit the loop when i is 4
}
printf("%d\n", i);
}
return 0;
}
break
and continue
can manipulate the flow of loops. The continue
statement skips the current iteration when i
is 2, while the break
statement terminates the loop when i
becomes 4, demonstrating how to control the execution flow effectively.