24.1k views
5 votes
The difference between a for loop and a while loop is that a for loop is a loop that happens for a certain number of times. A while loop happens until a certain condition is met. How do you know when to use each one? Give specific examples in your answer.

User Kalina
by
3.5k points

2 Answers

6 votes

Answer:

Say that you want to print 6 times you create a loop for the printing process

Step-by-step explanation:

Hope this helps

User Ergelo
by
3.7k points
2 votes

Answer:

When we know how many times a loop is going to occur when we make use of them for a loop. Like if we want to print a number 100 times, then we make use of them for a loop. However, if we only know the condition then we make use of the while loop.

Like while( sum<=100):

sum +=i

i=i+1

And this will add till sum <=100.

Hence, while requires us to know the number of times the loop will take place. And while requires a condition. On many occasions, both can be used. However, it must be understood that we increment the loop number at the end in case of the while loop and the beginning in case of a loop.

Step-by-step explanation:

Please check the answer section.

User MrDrews
by
3.1k points