0

can we always replace for loop with while loops nd vice versa?

3rd Oct 2016, 7:22 PM
pulkit
pulkit - avatar
4 odpowiedzi
+ 4
Mythos is partially correct. for() loop can always be replaced with while() loop, but sometimes, you cannot use for() loop and while() loop must be used. I am going to dig deeper. for() loop is called 'counted loop', meaning if you know how many times you will run the loop, such as going through an entire array (this is called iterating). for() loop is recommended for cases like this. meanwhile, while() loop (ha, get it) is called 'conditional loop' and is usually used when you don't know howmany times something will be running. For example, if you need player's name and it has to be less than 10 characters, you don't know how many times the player will be dumb and try to input "XxsuperawesomedudexX". in this case, while() must be used. okay, fine, being super duper picky, you CAN use for() loop by doing for(int i = 0; i == 0;){} then adding 1 to i when the name is within 10 characters, but that's just bad. was anything confusing?
4th Oct 2016, 5:43 AM
dragonbro1015
dragonbro1015 - avatar
+ 1
Yes, of course. For purposes of use and readability, there are advantages of picking one over the other.
3rd Oct 2016, 10:50 PM
Mythos
0
Thnq guys!!
4th Oct 2016, 1:59 PM
pulkit
pulkit - avatar
0
for converting for loop while(condition) { cin<<(increment..as desired); cout>>(statement) } for converting while loop to for loop for(assign var. a value;condition for var;updation of var.) { (statement); } hope this helps :-)
8th Oct 2016, 3:13 PM
bhavyaa