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

Iterating Over Dictionary Key Values Corresponding to List in Python

Working in Python 2.7. I have a dictionary with team names as the keys and the amount of runs scored and allowed for each team as the value list: NL_East = {'Phillies': [645, 469], 'Braves': [599, 548], 'Mets': [653, 672]} I would like to be able…
Burton Guster
  • 2,213
  • 8
  • 31
  • 29
140
votes
7 answers

Python : List of dict, if exists increment a dict value, if not append a new dict

I would like do something like that. list_of_urls = ['http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.cn/', 'http://www.google.com/', 'http://www.google.fr/', 'http://www.google.fr/', …
Natim
  • 17,274
  • 23
  • 92
  • 150
138
votes
8 answers

How to for_each through a list(objects) in Terraform 0.12

I need to deploy a list of GCP compute instances. How do I loop for_each through the "vms" in a list of objects like this: "gcp_zone": "us-central1-a", "image_name": "centos-cloud/centos-7", "vms": [ { "hostname":…
TheShadow2707
  • 2,441
  • 3
  • 8
  • 8
138
votes
6 answers

How to iterate over array of objects in Handlebars?

This might seem a silly question but I can't seem to find the answer anywhere. I'm hitting this Web API that returns an array of objects in JSON format: Handlebars docs shows the following example:
    {{#each people}} …
empz
  • 11,509
  • 16
  • 65
  • 106
137
votes
5 answers

Do while loop in SQL Server 2008

Is there any method for implement do while loop in SQL server 2008?
Nithesh Narayanan
  • 11,481
  • 34
  • 98
  • 138
136
votes
19 answers

Is it faster to count down than it is to count up?

Our computer science teacher once said that for some reason it is faster to count down than to count up. For example if you need to use a FOR loop and the loop index is not used somewhere (like printing a line of N * to the screen) I mean that code…
Bob
  • 2,586
  • 7
  • 20
  • 33
134
votes
2 answers

Why do you have to call .items() when iterating over a dictionary in Python?

Why do you have to call items() to iterate over key, value pairs in a dictionary? ie. dic = {'one': '1', 'two': '2'} for k, v in dic.items(): print(k, v) Why isn't that the default behavior of iterating over a dictionary for k, v in dic: …
Falmarri
  • 47,727
  • 41
  • 151
  • 191
133
votes
20 answers

How can I escape white space in a bash loop list?

I have a bash shell script that loops through all child directories (but not files) of a certain directory. The problem is that some of the directory names contain spaces. Here are the contents of my test directory: $ls -F test Baltimore/ Cherry…
MCS
  • 22,113
  • 20
  • 62
  • 76
132
votes
6 answers

Can you 'exit' a loop in PHP?

I have a loop that is doing some error checking in my PHP code. Originally it looked something like this... foreach($results as $result) { if (!$condition) { $halt = true; ErrorHandler::addErrorToStack('Unexpected result.'); …
alex
  • 479,566
  • 201
  • 878
  • 984
132
votes
4 answers

Loop through each row of a range in Excel

This is one of those things that I'm sure there's a built-in function for (and I may well have been told it in the past), but I'm scratching my head to remember it. How do I loop through each row of a multi-column range using Excel VBA? All the…
Margaret
  • 5,749
  • 20
  • 56
  • 72
130
votes
6 answers

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

I found out a curious thing today and was wondering if somebody could shed some light into what the difference is here? import numpy as np A = np.arange(12).reshape(4,3) for a in A: a = a + 1 B = np.arange(12).reshape(4,3) for b in B: b +=…
Dammi
  • 1,268
  • 2
  • 13
  • 23
129
votes
6 answers

Iterate over two arrays simultaneously in bash

I have two arrays. array=( Vietnam Germany Argentina ) array2=( Asia Europe America ) I want to loop over these two arrays simulataneously, i.e. invoke a command on the first elements of the two arrays, then invoke the same command on…
user2354862
  • 1,291
  • 2
  • 8
  • 3
128
votes
7 answers

Scala downwards or decreasing for loop?

In Scala, you often use an iterator to do a for loop in an increasing order like: for(i <- 1 to 10){ code } How would you do it so it goes from 10 to 1? I guess 10 to 1 gives an empty iterator (like usual range mathematics)? I made a Scala script…
Felix
  • 8,385
  • 10
  • 40
  • 59
126
votes
10 answers

Looping through localStorage in HTML5 and JavaScript

So, I was thinking I could just loop through localStorage like a normal object as it has a length. How can I loop through this? localStorage.setItem(1,'Lorem'); localStorage.setItem(2,'Ipsum'); localStorage.setItem(3,'Dolor'); If I do a…
Oscar Godson
  • 31,662
  • 41
  • 121
  • 201
125
votes
16 answers

Indexes of all occurrences of character in a string

The following code will print 2 String word = "bannanas"; String guess = "n"; int index; System.out.println( index = word.indexOf(guess) ); I would like to know how to get all the indexes of "n" ("guess") in the string "bannanas" The expected…
Trufa
  • 39,971
  • 43
  • 126
  • 190