For and while loop comparison
Comparing simple for and while loop with a simple number printing example
- Comparison between for and while loops.
using namespace std;
Test it !
Test it !
Before using this you should have copied the code by selecting the entire code and pressing cntrl-c. (Line numbers will not come in the copied code). After that open any of the service and press cntrl-v to paste in the given code area. Needs a bit of tweaking as per the link.
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.
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.
- 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
sunmitra| Created: 28-Dec-2017 | Updated: 30-Jan-2018|