Which Loop to Use?

Learn when to use "for" and when to use the "while" loop in the code.

We'll cover the following

Discussion

for loops are great because they include the notion of counting by default, avoiding the problem of infinite loops. However, it means you have to know how many times you want the loop to run as soon as you write your code. For situations where you don’t already know how many times the code should run, while loops make sense.

while loop example

Here’s a while loop use case in which a random number from 0 - 9 is given. The loop keeps incrementing the number until it reaches 10 and then terminates.

Get hands-on with 1400+ tech skills courses.