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
192
votes
15 answers

How can I make sense of the `else` clause of Python loops?

Many Python programmers are probably unaware that the syntax of while loops and for loops includes an optional else: clause: for val in iterable: do_something(val) else: clean_up() The body of the else clause is a good place for certain…
alexis
  • 48,685
  • 16
  • 101
  • 161
191
votes
12 answers

How to add an integer to each element in a list?

If I have list=[1,2,3] and I want to add 1 to each element to get the output [2,3,4], how would I do that? I assume I would use a for loop but not sure exactly how.
user1212818
185
votes
7 answers

Check if key exists and iterate the JSON array using Python

I have a bunch of JSON data from Facebook posts like the one below: {"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id":…
pravi
  • 2,029
  • 3
  • 13
  • 9
183
votes
12 answers

Loop through a date range with JavaScript

Given two Date() objects, where one is less than the other, how do I loop every day between the dates? for(loopDate = startDate; loopDate < endDate; loopDate += 1) { } Would this sort of loop work? But how can I add one day to the loop…
Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
180
votes
4 answers

Twig for loop for arrays with keys

I use Twig and I have an array with keys like this: array[1] = "alpha" array[2] = "bravo" array[3] = "charlie" array[8] = "delta" array[9] = "echo" And I would like to get the key (1,2,3,8,9) and the content (alpha, bravo, charlie, delta, echo) in…
Guillaume
  • 8,741
  • 11
  • 49
  • 62
179
votes
10 answers

Loop through a comma-separated shell variable

Suppose I have a Unix shell variable as below variable=abc,def,ghij I want to extract all the values (abc, def and ghij) using a for loop and pass each value into a procedure. The script should allow extracting arbitrary number of comma-separated…
Ramanathan K
  • 1,829
  • 3
  • 13
  • 8
178
votes
34 answers

Looping in a spiral

A friend was in need of an algorithm that would let him loop through the elements of an NxM matrix (N and M are odd). I came up with a solution, but I wanted to see if my fellow SO'ers could come up with a better solution. I'm posting my solution as…
Can Berk Güder
  • 109,922
  • 25
  • 130
  • 137
174
votes
11 answers

How to find the most recent file in a directory using .NET, and without looping?

I need to find the most recently modified file in a directory. I know I can loop through every file in a folder and compare File.GetLastWriteTime, but is there a better way to do this without looping?.
Chris Klepeis
  • 9,783
  • 16
  • 83
  • 149
171
votes
1 answer

Javascript efficiency: 'for' vs 'forEach'

What is the current standard in 2017 in Javascript with for() loops vs a .forEach. I am currently working my way through Colt Steeles "Web Dev Bootcamp" on Udemy and he favours forEach over for in his teachings. I have, however, searched for various…
tonyrobbins
  • 1,733
  • 2
  • 9
  • 6
169
votes
13 answers

Is there any overhead to declaring a variable within a loop? (C++)

I am just wondering if there would be any loss of speed or efficiency if you did something like this: int i = 0; while(i < 100) { int var = 4; i++; } which declares int var one hundred times. It seems to me like there would be, but I'm not…
user98188
168
votes
5 answers

C# Iterate through Class properties

I'm currently setting all of the values of my class object Record. This is the code that I'm using to populate the record at the moment, property by property. // Loop through each field in the result set for (int i = 0; i <= resultItems.Length;…
Luke
  • 22,826
  • 31
  • 110
  • 193
164
votes
5 answers

PHP Foreach Pass by Reference: Last Element Duplicating? (Bug?)

I just had some very strange behavior with a simple php script I was writing. I reduced it to the minimum necessary to recreate the bug:
regality
  • 6,496
  • 6
  • 29
  • 26
164
votes
16 answers

Checking if array is multidimensional or not?

What is the most efficient way to check if an array is a flat array of primitive values or if it is a multidimensional array? Is there any way to do this without actually looping through an array and running is_array() on each of its elements?
Wilco
  • 32,754
  • 49
  • 128
  • 160
161
votes
6 answers

Loop a multidimensional array and only print two specific column values per row

How can I print the filepath and filename values from each row? Array ( [0] => Array ( [fid] => 14 [list] => 1 [data] => Array ( [alt] => [title] => …
esafwan
  • 17,311
  • 33
  • 107
  • 166
161
votes
3 answers

How to loop through key/value object in Javascript?

var user = {}; now I want to create a setUsers() method that takes a key/value pair object and initializes the user variable. setUsers = function(data) { // loop and init user } where data is like: 234: "john", 23421: "smith", ....
Blankman
  • 259,732
  • 324
  • 769
  • 1,199