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
Run Output
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
