In C, Loops are fundamental constructs in programming that allow us to repeat a block of code multiple times.
In C programming, there are mainly three types of loops: "for", "while", and "do-while".
Each loop type has its own syntax and use cases.
The "for" loop is commonly used when we know the number of iterations in advance.
for (initialization; condition; update) { // Code to be executed }
Iterating over the number value, in our case condition is `3`.
#include <stdio.h> int main() { int i; for (i = 0; i < 3; i++) { printf("Iterating value: %d \n", i); } return 0; }
Iterating value: 0 Iterating value: 1 Iterating value: 2
when we enter in the for loop `i` variable is initialized to 0 and it checks condition `0` is less than 3 and the condition becomes true, so it will print `Iterating value: 0`, in the `for` loop statement and we also update the `i` value as well using `i++`.
Now, the `i` variable value is 1, and `1` is less than 3 so it will print the `Iterating value: 1` and increment the value of the `i` variable by 1. now the `i` value is 2.
During the 3rd iteration, it checks condition `i` is less than 3 and currently `i` value is 2, so it will iterate again and print `Iterating value: 2` and increment the value of `i` variable by 1.
During the 4th iteration, it checks condition `i`. 3 is less than 3 so it becomes false and comes out from the for loop and will not print anything.
The "while" loop is used when the number of iterations is not known beforehand, and the loop continues as long as the condition is true.
while (condition) { // Code to be executed }
#include <stdio.h> int main() { int i = 0; while (i < 3) { printf("Iterating Value: %d ", i); i++; } return 0; }
In While Loop, we need to initialize our condition value before entering into the loop. Currently `i` value is 0 and 0 is less than 3. so it will print `Iterating Value: 0` and inside the while loop we are updating the `i` value using the statement `i++`.
Similarly, it will do when the `i` value is 1 and update the `i` value to 2.
Now, the `i` value is 2, and the condition `2 < 3` becomes true, so it enters in the condition and prints `Iterating Value: 2` and it will also increase the `i` value by 1 and now the `i` value is 3.
During the 4th iteration, it checks condition `i`. 3 is less than 3 so it becomes false and comes out from the while loop and will not print anything.
The "do-while" loop is similar to the "while" loop, but it guarantees that the code block executes at least once before checking the condition.
do { // Code to be executed } while (condition);
#include <stdio.h> int main() { int i = 0; do { printf("%d ", i); i++; } while (i < 3); return 0; }
Each type of loop has its own strengths and use cases.
It's essential to choose the appropriate loop based on the specific requirements of your program.