0

Is there any actual difference between for and while loops?

Can you do everything you can do in a for loop in a while loop and vice versa? Or are there any situations where only for loops (or while loops) work?

22nd Aug 2016, 2:15 AM
MoroAstray
MoroAstray - avatar
4 Réponses
+ 3
The 'for' loop and 'while' loop can be used interchangeably in most cases: the 'while' loop is designed to run a loop as long as the condition is true - no matter what. And the 'for' loop is meant to be set up with a limit in mind. The 'while' loop can have a limit, and the 'for' loop can be set up to run indefinitely; but it's more efficient to use the loops for functions that they are set up for most effectively. Basically: It's neater and more efficient to use the 'while' loop when you don't know the maximum number of times it will loop (like a function designed to scan something at intervals and record whatever it scans). 'for' loops are best utilized when you want to limit the amount of times something will loop (like a function designed to check that a program has initialized correctly: once it checks a certain number of times and confirmed everything is good, it doesn't need to check anymore until the next start up of the program). TL:DR Depending on what the loop does and how often it needs to run, it's more efficient and cleaner to use the loop for what it was designed to do best. You won't really notice the difference with a small program, but a large program with enough inefficiencies will be sluggish. I'll call it one form of optimization. Edit: Just found this written by Michael B. "Some extra details on ALL loops: How I like to remember what loop I should be using is by asking myself if I want to perform a function repeatedly until some condition is met (while loop) or if I am performing an action on a collection (foreach loop), or if I'm using the index value of a collection to perform an action (for loop)"
24th Aug 2016, 7:30 AM
Greg
+ 1
I think its the same... TG he dif is just in the condition statement
22nd Aug 2016, 6:53 AM
avy7352
avy7352 - avatar
0
Yes, their functions are just the same. And yes again, everything you can do at WHILE, FOR and DO-WHILE can also be done using other loops.
22nd Aug 2016, 11:31 AM
Erwin Mesias
Erwin Mesias - avatar
0
you can assign values to variable under for loop condition if int x; has no value you can use this under for loop condition not in while or do while
22nd Sep 2016, 11:26 AM
Nitin Moorpani
Nitin Moorpani - avatar