![]() |
VOOZH | about |
In C, loops are the fundamental part of language that are used to repeat a block of code multiple times. The two most commonly used loops are the for loop and the while loop. Although they achieve the same result, their structure, use cases, and flexibility differ.
The below table highlights some primary differences between the for and while loop in C:
| Feature | For Loop | While Loop |
|---|---|---|
| Purpose | Used when the number of iterations is known beforehand. | Used when the number of iterations is unknown and depends on a condition. |
| Structure | Combines initialization, condition, and increment/decrement in a single line. | Requires separate statements for initialization, condition, and increment/decrement. |
| Syntax | for (initialization; condition; update) { // statements.... } | while (condition) { // statements... } |
| Condition Check | The condition is checked before each iteration (entry-controlled). | The condition is checked before each iteration (entry-controlled). |
| Use Case | Ideal for counting or iterating over arrays, loops with fixed limits. | Ideal for loops with dynamic conditions, like reading input until a condition is met. |
The for loop is best suited for scenarios where the number of iterations is known or fixed beforehand. It's a structured loop that combines initialization, condition checking, and iteration in a single line as a part of its syntax.
Syntax
for (initialization; condition; updation) {
// Body of the loop
}
Let's take a look at an example that prints the text "GfG" 5 times.
GfG GfG GfG GfG GfG
The while loop, on the other hand, is more flexible and is often used when the number of iterations is not known upfront. It only requires the condition to be checked before each iteration and will continue running as long as the condition evaluates to true.
Syntax
while (condition) {
// Body
}
Let's take a look at an example that prints the text "GfG" 5 times.
Loop Loop Loop Loop Loop
After looking at these examples, one may wonder whether there is any case when the two loops do not work in the same way? The answer is YES. Due to the structural differences, if there are some jump statements in the code, for and while loop may execute in different way.
Let's take an example where a continue statement is present in the loop body. For look at for loop:
0 1 3 4
Now look at while loop:
Output
Time Limit Exceeded
The problem in the above while Loop Code is that, when the condition (i == 2) becomes true the continue statement gets executed, which will take you again to the beginning of the loop without incrementing i. Due to this, the process will continue infinitely which leads to “Time Limit Exceeded” as the output.
Now, to solve this problem we have to do a small correction in the code as shown below:
0 1 3 4