Questions tagged [loops]

Loops are a type of control flow structure in programming in which a series of statements may be executed repeatedly until some condition is met.

A loop is a fundamental programming idea that is commonly used in writing programs.

Types

A loop can be categorized in two different ways,

1. Entry Controlled Loops

A loop which checks for the condition before the iteration is known as Entry Controlled loops - for example

  • while loop - iterates while a certain condition is true
  • until loop - iterates while a certain condition is false
  • for loop - iterates through numbers in a certain range. Note: not the same as C++ for loop
  • foreach loop - iterates through the elements of a collections.

2. Exit Controlled Loops

A loop which checks the condition after the iteration is knows as Exit Controlled loop - for example

  • do-while loop - iterates while a certain condition is true (the first iteration will run regardless of the condition)
  • do-until loop - iterates while a certain condition is false (the first iteration will run regardless of the condition)

Most languages provide only a subset of loop types described above. For example: in Python there are only foreach (keyword for) and while loops.

Break and continue

In some languages, there are two keywords that simplify the task of implementing a more advanced control flow: break and continue. The former allows you to jump to the operator immediately after the loop, the latter allows you to jump to the end of the current iteration.

Example: implementation of do-until loop in Python using the break keyword:

while True:
    // loop body
    if condition:
        break

Tag usage

The tag can be used for programming related problems in implementing loops feature of any programming language. Please avoid theoretical questions related to tag on stackoverflow.

See also:

Read more

95843 questions
604
votes
13 answers

How do I iterate over a JSON structure?

I have the following JSON structure: [{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }] How do I iterate over it using JavaScript?
Flueras Bogdan
  • 9,187
  • 8
  • 32
  • 30
599
votes
28 answers

How to remove elements from a generic list while iterating over it?

I am looking for a better pattern for working with a list of elements which each need processed and then depending on the outcome are removed from the list. You can't use .Remove(element) inside a foreach (var element in X) (because it results in…
InvertedAcceleration
  • 10,695
  • 9
  • 46
  • 71
508
votes
26 answers

Why does this go into an infinite loop?

I have the following code: public class Tests { public static void main(String[] args) throws Exception { int x = 0; while(x<3) { x = x++; System.out.println(x); } } } We know he should have…
The Student
  • 27,520
  • 68
  • 161
  • 264
499
votes
33 answers

How do I add a delay in a JavaScript loop?

I would like to add a delay/sleep inside a while loop: I tried it like this: alert('hi'); for(var start = 1; start < 10; start++) { setTimeout(function () { alert('hello'); }, 3000); } Only the first scenario is true: after showing…
olidev
  • 20,058
  • 51
  • 133
  • 197
494
votes
14 answers

How can I avoid "RuntimeError: dictionary changed size during iteration" error?

Suppose I have a dictionary of lists: d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]} Now I want to remove key-value pairs where the values are empty lists. I tried this code: for i in d: if not d[i]: d.pop(i) but this gives an…
user1530318
  • 25,507
  • 15
  • 37
  • 48
483
votes
10 answers

Is there a "do ... while" loop in Ruby?

I'm using this code to let the user enter in names while the program stores them in an array until they enter an empty string (they must press enter after each name): people = [] info = 'a' # must fill variable with something, otherwise loop won't…
Paige Ruten
  • 172,675
  • 36
  • 177
  • 197
475
votes
20 answers

Is there a better way to run a command N times in bash?

I occasionally run a bash command line like this: n=0; while [[ $n -lt 10 ]]; do some_command; n=$((n+1)); done To run some_command a number of times in a row -- 10 times in this case. Often some_command is really a chain of commands or a…
bstpierre
  • 30,042
  • 15
  • 70
  • 103
450
votes
1 answer

Scalaz iteratees: "Lifting" `EnumeratorT` to match `IterateeT` for a "bigger" monad

If I have an EnumeratorT and a corresponding IterateeT I can run them together: val en: EnumeratorT[String, Task] = EnumeratorT.enumList(List("a", "b", "c")) val it: IterateeT[String, Task, Int] = IterateeT.length (it &= en).run : Task[Int] If the…
lmm
  • 17,386
  • 3
  • 26
  • 37
442
votes
6 answers

Iterating over all the keys of a map

Is there a way to get a list of all the keys in a Go language map? The number of elements is given by len(), but if I have a map like: m := map[string]string{ "key1":"val1", "key2":"val2" }; How do I iterate over all the keys?
Martin Redmond
  • 13,366
  • 6
  • 36
  • 32
423
votes
5 answers

do { ... } while (0) — what is it good for?

I've been seeing that expression for over 10 years now. I've been trying to think what it's good for. Since I see it mostly in #defines, I assume it's good for inner scope variable declaration and for using breaks (instead of gotos.) Is it good for…
gilm
  • 7,690
  • 3
  • 41
  • 41
417
votes
8 answers

Breaking out of nested loops

Is there an easier way to break out of nested loops than throwing an exception? (In Perl, you can give labels to each loop and at least continue an outer loop.) for x in range(10): for y in range(10): print x*y if x*y > 50: …
Michael Kuhn
  • 8,302
  • 6
  • 26
  • 27
405
votes
30 answers

How to retry after exception?

I have a loop starting with for i in range(0, 100). Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will continue in the except clause (continue on to the next number for…
FurtiveFelon
  • 14,714
  • 27
  • 76
  • 97
402
votes
12 answers

What is the "right" way to iterate through an array in Ruby?

PHP, for all its warts, is pretty good on this count. There's no difference between an array and a hash (maybe I'm naive, but this seems obviously right to me), and to iterate through either you just do foreach (array/hash as $key => $value) In…
Tom Lehman
  • 85,973
  • 71
  • 200
  • 272
389
votes
9 answers

Declaring variables inside loops, good practice or bad practice?

Question #1: Is declaring a variable inside a loop a good practice or bad practice? I've read the other threads about whether or not there is a performance issue (most said no), and that you should always declare variables as close to where they are…
JeramyRR
  • 4,273
  • 3
  • 20
  • 20
387
votes
12 answers

Pythonic way to combine for-loop and if-statement

I know how to use both for loops and if statements on separate lines, such as: >>> a = [2,3,4,5,6,7,8,9,0] ... xyz = [0,12,4,6,242,7,9] ... for x in xyz: ... if x in a: ... print(x) 0,4,6,7,9 And I know I can use a list comprehension to…
ChewyChunks
  • 4,449
  • 3
  • 22
  • 14