0
For vs While?
What is the difference? and could you give me an example where can we use it
2 Answers
+ 8
for is meant for when you know exactly how many loops you want to do. Ex: If you're running a game that goes for 5 rounds. You can create and increment the counter right at the top and easily keep track of it.
while is when you don't know how long a loop will run. Ex: If you're running a program that receives inputs until a user enters a certain value.
+ 2
You can switch between both for and while loop . Both can be used to create a counter loop ( where you know the definite count of iterations) or a sentinel loop ( where you don't know definite count of iterations ). The difference is that, for loop being a single statement ( syntax : for(initialization,condition,updation) ) it is handy for counter loops . And in the case of while loop , since only the condition is given with the keyword ... it is handy to be used as a sentinel loop . While loops are specifically handy for menu-driven programs