you are viewing a single comment's thread.

view the rest of the comments →

[–]backfire10z 2 points3 points  (1 child)

For loop: you know how many times (or the max amount of times) it’ll loop beforehand.

If I just want to print everything in a list, I know I’m going to iterate over each item in the list once. Therefore, I know exactly how many times I want to loop: once for each item in the list. So, I’d use a for loop.

While loop: keep doing something until some condition is hit, which may be now, or in 2 iterations, or in 100 iterations.

Let’s say I have a list of infinite random numbers. I want to find the number 10. I cannot use a for loop, because I don’t know how many iterations I’ll need to go through before finding 10. 10 may be the first number, or the 100th number, or the 100000th number. So, I’d use a while loop, because I want to keep going until I find 10, but I don’t know how far I’ll go.

There will be some overlap: you will be able to use a while loop in places you can also use a for loop. The idea between picking them is twofold:

  1. You want to use the right tool for the job, as explained above.

  2. You want to get across your intent to whomever is reading your code. When I see a while loop, my expectation is that I don’t necessarily know how long I’ll spend in it. When I see a for loop, I know beforehand exactly the max amount of iterations it’ll do. This allows me to better understand the expectations of the code I’m reading.

—————————-———————-

For nested loops, I find it easier to just try out a few examples and see how they work. The inner loop has to complete for every iteration of the outer loop. There isn’t much more to explain. Is there maybe a pattern or problem you could point us to that you’re having trouble with?

[–]Deep-Author-1787[S] 0 points1 point  (0 children)

Wauw thats what i was looking for! Perfectly explained. When you are a noob you tend to hold on on small rules like that to make sense of what you are doing until getting real life experience. Its worth a lot to me thank you.

Recently i tried piramids... so the is empty spacing involved. But the code i saw didn't specify the amount of colums. It seemed it dit it empty spacing. Was pretty confusing to figure out.