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
104
votes
5 answers

More Pythonic Way to Run a Process X Times

Which is more pythonic? While loop: count = 0 while count < 50: print "Some thing" count = count + 1 For loop: for i in range(50): print "Some thing" Edit: not duplicate because this has answers to determine which is clearer, vs. how…
Lionel
  • 3,188
  • 5
  • 27
  • 40
104
votes
9 answers

Tell the end of a .each loop in ruby

If i have a loop such as users.each do |u| #some code end Where users is a hash of multiple users. What's the easiest conditional logic to see if you are on the last user in the users hash and only want to execute specific code for that last…
Splashlin
  • 7,225
  • 12
  • 46
  • 50
101
votes
4 answers

Lambda in a loop

Considering the following code snippet: # directorys == {'login': , 'home': } for d in directorys: self.command["cd " + d] = (lambda : self.root.change_directory(d)) I expect to create a dictionary of two function…
FunkySayu
  • 7,641
  • 10
  • 38
  • 61
98
votes
8 answers

Looping from 1 to infinity in Python

In C, I would do this: int i; for (i = 0;; i++) if (thereIsAReasonToBreak(i)) break; How can I achieve something similar in Python?
user2058002
98
votes
4 answers

Looping through python regex matches

I want to turn a string that looks like this: ABC12DEF3G56HIJ7 into 12 * ABC 3 * DEF 56 * G 7 * HIJ I want to construct the correct set of loops using regex matching. The crux of the issue is that the code has to be completely general because I…
da5id
  • 1,039
  • 1
  • 9
  • 6
98
votes
3 answers

How to reverse tuples in Python?

Is this possible? Doesn't have to be in place, just looking for a way to reverse a tuple so I can iterate on it backwards.
Joan Venge
  • 315,713
  • 212
  • 479
  • 689
97
votes
12 answers

Strange result when removing item from a list while iterating over it in Python

I've got this piece of code: numbers = list(range(1, 50)) for i in numbers: if i < 20: numbers.remove(i) print(numbers) But, the result I'm getting is: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,…
Finger twist
  • 3,546
  • 9
  • 42
  • 52
96
votes
13 answers

How to make for loops in Java increase by increments other than 1

If you have a for loop like this: for(j = 0; j<=90; j++){} It works fine. But when you have a for loop like this: for(j = 0; j<=90; j+3){} it doesn't work. Could someone please explain this to me?
TomLisankie
  • 3,785
  • 7
  • 28
  • 32
95
votes
5 answers

Counter inside xsl:for-each loop

How to get a counter inside xsl:for-each loop that would reflect the number of current element processed. For example my source XML is The Unbearable Lightness of Being
kristof
  • 52,923
  • 24
  • 87
  • 110
95
votes
6 answers

How to render a tree in Twig

I would like to render a tree with an undetermined depth (children of children of children, etc.). I need to loop through the array recursively; how can I do this in Twig?
T-RonX
  • 1,053
  • 1
  • 9
  • 7
95
votes
10 answers

Why are memcpy() and memmove() faster than pointer increments?

I am copying N bytes from pSrc to pDest. This can be done in a single loop: for (int i = 0; i < N; i++) *pDest++ = *pSrc++ Why is this slower than memcpy or memmove? What tricks do they use to speed it up?
wanderer
  • 1,219
  • 1
  • 10
  • 10
92
votes
6 answers

When should I call SaveChanges() when creating 1000's of Entity Framework objects? (like during an import)

I am running an import that will have 1000's of records on each run. Just looking for some confirmation on my assumptions: Which of these makes the most sense: Run SaveChanges() every AddToClassName() call. Run SaveChanges() every n number of…
John B
  • 20,062
  • 35
  • 120
  • 170
91
votes
0 answers

Why are we using i as a counter in loops?

Why are we using for (int i = 0 ; i < count ; i++){ } Why the i? Why not for (int a = 0; a < count; a++){ } I do it, you do it, everyone does it, but WHY? *Edit I found out an old saying about Fortran which is more funny than correct which says…
Eric
  • 19,525
  • 19
  • 84
  • 147
90
votes
19 answers

Is there ever a need for a "do {...} while ( )" loop?

Bjarne Stroustrup (C++ creator) once said that he avoids "do/while" loops, and prefers to write the code in terms of a "while" loop instead. [See quote below.] Since hearing this, I have found this to be true. What are your thoughts? Is there an…
Dustin Boswell
  • 6,114
  • 7
  • 28
  • 26
90
votes
11 answers

more modern way of looping through C++ arrays

Recently I have found a lot of examples, most of them regards the C++ 98, anyways I have created my simple-array and a loop (codepad): #include using namespace std; int main () { string texts[] = {"Apple", "Banana", "Orange"}; for(…
Lucas
  • 3,517
  • 13
  • 46
  • 75