Difference between for loop and while loop
Programming

Difference between for loop and while loop

Mishel Shaji
Mishel Shaji


Both for loop and while loop is used to execute a statement or a set of statements until an expression is evaluated to false. The difference between for loop and while loop is as follows:

Syntax

A for loop has three parts. 1) Initialization 2) Condition and 3) An operation to be performed each time the loop is executed.

for(int i=0; i<10; i++)
{
	//statements
}
//This may not be same for all programming languages

Unlike for loop, while loop will have only one expression. The loop will be executed until the expression is evaluated to false.

while(i>0)
{
	//statements
}

Usage

  • A for loop is used when you know the exact number of iteration to execute the statements.
  • While loop is used when you are unsure about the number of iterations which the statements should be executed.

Example

This is a program to add the numbers entered by the user until he/she hits 0.

*Code may vary for different programming languages.

Using while loop

int r = 0;
int opt = 1;
while (opt != 0)
{
     Console.WriteLine("Enter a number to add");
     Console.WriteLine("Press zero to exit");
     opt = Convert.ToInt32(Console.ReadLine());
     r = r + opt;
}
Console.WriteLine("The result is " + r);
Console.ReadLine();

Using for loop

int r = 0;
int opt = 1;
for (int i = 1; i <=1;i++ )
{
    i--;
    Console.WriteLine("Enter a number to add");
    Console.WriteLine("Press zero to exit");
    opt = Convert.ToInt32(Console.ReadLine());
    r = r + opt;
    if(opt==0)
    {
        i = 2;
    }
}
Console.WriteLine("The result is " + r);
Console.ReadLine();

From this example, it is clear that using while is a good choice when the exact number of iteration is unknown.

Working

A while loop will be executed as long as the given condition is satisfied. But in the case of  for loop:

  • A value is initialized (only for the first time).
  • An expression is evaluated.
  • The body of the loop is executed if the expression is evaluated to true.
  • An operation (++ or --) is performed.
  • The above three steps are repeated until the expression is evaluated to false.