For Versus While in C++


Loops in programming are used to compute a block of code multiple times. Here we will be seeing the difference between two types of loops in the program, For Loop and While Loop.

For Loop

For Loop is a type of repetition control loop which allows the user to loop over the given block of code upto a specific number of times.

Syntax

for(initisation; condition; update){
   …code to be repeated
}

While Loop

While loop is a type of entry-controlled loop that allows the user to repeatedly execute the given statement till the given condition is true.

Syntax

while(condition){
   …code to be repeated
}

Difference between For and While Loops

  • For loop is an interaction controlled loop whereas while is a condition controlled loop.

  • The condition statement of for loop allows users to add an update statement inside it whereas in while condition only the control expression can be written.

  • The test condition in for loop is commonly an integer comparison whereas in while the test condition can be any other expression that evaluates to a boolean value.

Code where both the loops can provide different solutions

One case, where both the loops act differently is the body of loop contains a continue statement which is before update statement in while but in for the update statement is present in the initialisation itself.

Example

Program to illustrate the working of our solution:(for loop)

#include<iostream>
using namespace std;

int main(){

   cout<<"Displaying for loop working with continue statement\n";
   for(int i = 0; i < 5; i++){
      if(i == 3)
      continue;
      cout<<"loop count "<<i<<endl;
   }
   return 0;
}

Output

Displaying for loop working with continue statement
loop count 0
loop count 1
loop count 2
loop count 4

Example 

Program to illustrate the working of our solution:(while loop)

#include<iostream>
using namespace std;

int main(){

   cout<<"Displaying for loop working with continue statement";
   int i = 0;
   while(i < 5){
      if(i == 3)
      continue;
      cout<<"loop count "<<i<<endl;
      i++;
   }
   return 0;
}

Output

Displaying for loop working with continue statementloop count 0
loop count 1
loop count 2

Updated on: 01-Feb-2022

128 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements