While loop and for loop
So while loop and for loop do the same thing but when do we use while and for loop, is there any particular role for while and for loop?
Joel Sprunger3,416 Points
A for loop is usually used for a loop that executes a set number of times and a while loop is something that executes until a condition is met. They can be used interchangeably by exiting the for loop, or by putting a counter in the while loop. I prefer to only use a for loop. If you do want to use a while loop, it is good to put some form of exit if the condition isn't met, otherwise it can turn into an infinite loop (usually because there is a logical bug). If you put a counter in the while loop and exit the loop if the counter gets above 10,000 then the loop will not lock up the program.