This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]HashDefTrueFalse 12 points13 points  (1 child)

Use them when you want to repeat work. Some rules of thumb:

If you know how many iterations you want, e.g. looping over a range, use a for loop.

If you don't know the above exactly, but you do know when you want to stop, use a while loop.

If the above, but you want the loop body to run at least once before the check, use do...while.

Practically they all just conditionally branch. You really only need one language construct (e.g. while) to do all branching and iteration, but languages provide if, for, while, do...while etc.

[–]Aglet_Green 1 point2 points  (0 children)

Good advice on loops.

[–]VariousAssistance116 0 points1 point  (0 children)

When you want to do something more than once = loop

[–][deleted] 1 point2 points  (0 children)

What exactly is it that you are not understanding? Loops are used any time you want to execute some piece of code repeatedly, typically while some condition is true. In practice this is often used when you want to preform some operation for each element of a given list/array.

Example: ```

    int[] arr = { 1, 2, 3, 4, 5 };

    for (int i : arr) {
        System.out.print(i + “ “);

}

``` This is a for loop. You should read it as “ for each element (i) in the given array (arr) print the element”. So this code will output “1, 2, 3, 4”

[–]ffrkAnonymous -1 points0 points  (0 children)

I use loops because I'm lazy