Open In App

Difference between For Loop and While Loop in Programming

Both for loops and while loops are control flow structures in programming that allow you to repeatedly execute a block of code. However, they differ in their syntax and use cases. It is important for a beginner to know the key differences between both of them.

Difference between For Loop and While Loop

Difference between For Loop and While Loop

For Loop in Programming:

Example:

#include <iostream>
using namespace std;

int main()
{
    for (int i = 0; i < 5; i++)
        cout << i << "\n";
    return 0;
}
#include &lt;stdio.h&gt;

int main()
{
    for (int i = 0; i &lt; 5; i++) {
        printf(&quot;%d\n&quot;, i);
    }
    return 0;
}
public class Main {
    public static void main(String[] args) {
        // For loop to print numbers from 0 to 4
        for (int i = 0; i < 5; i++) {
            System.out.println(i);
        }
    }
}
for i in range(5):
    print(i)
// For loop to print numbers from 0 to 4
for (let i = 0; i < 5; i++) {
    console.log(i);
}

Output
0
1
2
3
4

This prints the numbers 0 through 4.

While Loop in Programming:

Example:

#include <iostream>
using namespace std;

int main()
{
    int count = 0;
    while (count < 5) {
        cout << count << "\n";
        count += 1;
    }
    cout << endl;
    return 0;
}
#include &lt;stdio.h&gt;

int main()
{
    int count = 0;
    while (count &lt; 5) {
        printf(&quot;%d\n&quot;, count);
        count += 1;
    }
    return 0;
}
public class Main {
    public static void main(String[] args) {
        int count = 0;

        // Example: While loop to print numbers from 0 to 4
        while (count < 5) {
            System.out.println(count);
            count += 1;
        }

        System.out.println();
    }
}
count = 0
while count &lt; 5:
    print(count)
    count += 1
let count = 0;
while (count < 5) {
    console.log(count);
    count += 1;
}
console.log();

Output
0
1
2
3
4

This prints the numbers 0 through 4, similar to the for loop example.

Difference between For Loop and While Loop in Programming:

Key differences between for and while loops:

Featurefor Loopwhile Loop
InitializationDeclared within the loop structure and executed once at the beginning.Declared outside the loop; should be done explicitly before the loop.
ConditionChecked before each iteration.Checked before each iteration.
UpdateExecuted after each iteration.Executed inside the loop; needs to be handled explicitly.
Use CasesSuitable for a known number of iterations or when looping over ranges.Useful when the number of iterations is not known in advance or based on a condition.
Initialization and Update ScopeLimited to the loop body.Scope extends beyond the loop; needs to be handled explicitly.

Choose between for and while loops based on the specific requirements of your program and the nature of the problem you are solving.

Article Tags :