The for
loop and the while
loop are both used for iteration, but they differ in their syntax and usage:
For loop: It is typically used when the number of iterations is known beforehand. The syntax is more compact and structured, consisting of three parts: initialization, condition, and update. It’s used for situations where a loop will run a set number of times. Example:
- for(int i = 0; i < 5; i++) {
printf(“%d\n”, i);
}
While loop: This loop runs as long as the condition is true, and it is often used when the number of iterations is unknown and depends on a certain condition. It only has a condition part and is more flexible but may result in infinite loops if the condition is not correctly handled. Example:
- int i = 0;
while(i < 5) {
printf(“%d\n”, i);
i++;
}