For and while loop comparison – Computer Sir Ki Class
  

Login
[lwa]



Code Learning #CPP#1995 siteicon   siteicon   siteicon  

For and while loop comparison

Comparing simple for and while loop with a simple number printing example

Learning Objectives

  • Comparison between for and while loops.

Source Code

TC++ #1995

#include <iostream.h>
#include <conio.h>
int main()
{
clrscr();
for(int i=1;i<=10;i++)
cout<<i<<" ";
cout<<endl;
int j=1;
while(j<=10)
{
cout<<j<<" ";
j++;
}
cout<<endl;
getch();
return 0;
}

Source Code

#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=10;i++)
cout<<i<<" ";
cout<<endl;
int j=1;
while(j<=10)
{
cout<<j<<" ";
j++;
}
cout<<endl;
return 0;
}

Test it !

Run Output

1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

Code Understanding

for(int i=1;i<=10;i++)
cout<<i<<” “;
This is simple for loop with three instructions given in the first line itself. The index variable of for loop if it has been declared within the first line of loop will not be accessible after the loop (As per new C++11 ISO standard). This allow reuse of index variables for other loops.

int j=1;
while(j<=10)
{
cout<<j<<” “;
j++;
}
This is equivalent while loop with different index variable j. Here the initialisation is outside while loop just before it and only condition is checked in the while line. The loop counter i++ is given as the last line of while loop. The while loop is visibly large in implementation but it has the index variable accessible even outside the loop.

Notes

  • Most modern programmers prefer for loops over while loop as the first choice, but the choice is mainly dependent on need of common index variables for many loops or reuse of index variable is more preferable.


Suggested Filename(s): for-and-while.cpp



Share

sunmitra| Created: 28-Dec-2017 | Updated: 30-Jan-2018|






Back