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
9
votes
2 answers

How can I loop through each character in a string in Elixir?

Say I have a huge body of text ~500 chars stored in a string, how can i loop through the string and increment a variable by 1 every time i encounter the character 'a'?
frostmage
  • 109
  • 1
  • 1
  • 3
9
votes
2 answers

Dynamic self-referencing conditional in list comprehension

Goal: Create a conditional statement in a list comprehension that (1) dynamically tests -- i.e., upon each iteration -- if the element is not in the list being comprehended given (2) the list is itself updated on each iteration. Background code: arr…
va01
  • 301
  • 2
  • 7
9
votes
3 answers

jQuery Closures, Loops and Events

I have a question similar to the one here: Event handlers inside a Javascript loop - need a closure? but I'm using jQuery and the solution given seems to fire the event when it's bound rather than on click. Here's my code: for(var i in…
Rob Stevenson-Leggett
  • 35,279
  • 21
  • 87
  • 141
9
votes
9 answers

How to transform string of space-separated key,value pairs of unique words into a dict

I've got a string with words that are separated by spaces (all words are unique, no duplicates). I turn this string into list: s = "#one cat #two dogs #three birds" out = s.split() And count how many values are created: print len(out) # Says 192…
magic_turtle
  • 1,243
  • 3
  • 17
  • 37
9
votes
3 answers

Javascript while loop return value

I have a simple question regarding while loop in Javascript. When I run this simple loop in browser console: var count = 0; while (count < 10) { console.log(count); count++; } The output to console log is 0,1,2...9. (as…
sachad
  • 307
  • 4
  • 13
9
votes
9 answers

php foreach: put each of the loop result in one variable

I think this is probably a very simple but I can get my head around! How can I put each of the loop result in one variable only? for instance, $employeeAges; $employeeAges["Lisa"] = "28"; $employeeAges["Jack"] = "16"; $employeeAges["Ryan"] =…
Run
  • 54,938
  • 169
  • 450
  • 748
9
votes
4 answers

MatPlotLib's ion() and draw() not working

I am trying to plot figures in real time using a for loop. I have the following simple code: import matplotlib.pyplot as plt plt.ion() plt.figure() for i in range(100): plt.plot([i], [i], 'o') plt.draw() plt.pause(0.0001) This code…
Alex
  • 93
  • 1
  • 1
  • 4
9
votes
1 answer

Creating a list of functions using a loop in R

In this introduction to functional programming, the author Hadley Wickham creates the following function factory: power <- function(exponent) { function(x) { x ^ exponent } } He then shows how this function can be used to define other…
David
  • 213
  • 1
  • 8
9
votes
2 answers

Javascript variable declaration within loop

I have a habit that I am borderline compulsive about, but I think may be completely unnecessary. With code like: function abc(){ var a,b; for(var i=0;i<10;i++){ a=document.getElementsByTagName('LI').item(i).width; …
dgo
  • 3,877
  • 5
  • 34
  • 47
9
votes
5 answers

Does C# have a nice way of iterating through every integer in a range, minus 1 of them?

The situation I have is like // radius is an int[] for ( int i = 0; i < radius.length; ++i ) { for ( int j = 0; j < radius.length; ++j ) { // do some stuff } } Except I actually want j to go through the range 0-radius.length, but…
user5648283
  • 5,913
  • 4
  • 22
  • 32
9
votes
4 answers

infinite loop in functional programming?

I was wondering: can infinite loops be done in functional programming? example: when using the windows API to get windows messages, it is usually implemented in a loop. I know it is possible to make a function that will keep going into recursion…
symbiont
  • 1,428
  • 3
  • 21
  • 27
9
votes
2 answers

Why is the time complexity of this loop non-linear?

Why is the time complexity of this loop non-linear and why is it so slow? The loop takes ~38s for N=50k, and ~570s for N=200k. Is there a faster way to do this? Rprof() seems to indicate that writing to memory is very slow. df <-…
Matt Munson
  • 2,903
  • 5
  • 33
  • 52
9
votes
1 answer

Is breaking out of an outer loop still applicable in Swift 2?

I am reading the book, Professional Swift by Michael Dippery @ 2015. And in the book, on page 25, he writes: "Both break and continue statements break out of the innermost loops. However, you can label loops, which enables you to break out of an…
George Lee
  • 814
  • 18
  • 34
9
votes
5 answers

How can loop through a list from a certain index?

I found the answer here but it doesn't work for me Accessing the index in Python 'for' loops I'm trying to loop from the second index ints = [1, 3, 4, 5, 'hi'] for indx, val in enumerate(ints, start=1): print indx, val for i in…
Eric MacLeod
  • 451
  • 3
  • 7
  • 18
9
votes
3 answers

TypeError: ufunc 'add' did not contain a loop

I use Anaconda and gdsCAD and get an error when all packages are installed correctly. Like explained here: http://pythonhosted.org/gdsCAD/ TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S32') dtype('S32')…
Raphael Pilz
  • 91
  • 1
  • 1
  • 5