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
117
votes
3 answers

Extract list of attributes from list of objects in python

I have an uniform list of objects in python: class myClass(object): def __init__(self, attr): self.attr = attr self.other = None objs = [myClass (i) for i in range(10)] Now I want to extract a list with some attribute of that…
lanwatch
  • 1,377
  • 2
  • 9
  • 9
116
votes
4 answers

How can I iterate over a string by runes in Go?

I wanted to this: for i := 0; i < len(str); i++ { dosomethingwithrune(str[i]) // takes a rune } But it turns out that str[i] has type byte (uint8) rather than rune. How can I iterate over the string by runes rather than bytes?
Matt
  • 21,026
  • 18
  • 63
  • 115
116
votes
17 answers

Loop that also accesses previous and next values

How can I iterate over a list of objects, accessing the previous, current, and next items? Like this C/C++ code, in Python? foo = somevalue; previous = next = 0; for (i=1; i
dir01
  • 2,120
  • 4
  • 18
  • 17
115
votes
20 answers

Get iteration index from List.map()

I wrote an iteration on list of letters and put inside cards on screen using "map" class. In the code you can see that I made a row, and using "map" printed all the userBoard on cards to the screen. I want to add some logic inside so I need to get…
Shoham yetzhak
  • 1,153
  • 2
  • 7
  • 6
114
votes
3 answers

Iterating through a golang map

I have a map of type: map[string]interface{} And finally, I get to create something like (after deserializing from a yml file using goyaml) mymap = map[foo:map[first: 1] boo: map[second: 2]] How can I iterate through this map? I tried the…
ashokgelal
  • 80,002
  • 26
  • 71
  • 84
114
votes
8 answers

C#: Looping through lines of multiline string

What is a good way to loop through each line of a multiline string without using much more memory (for example without splitting it into an array)?
flamey
  • 2,311
  • 4
  • 33
  • 40
112
votes
3 answers

Equivalent VB keyword for 'break'

I just moved over to the Visual Basic team here at work. What is the equivalent keyword to break in Visual Basic, that is, to exit a loop early but not the method?
Tyronomo
  • 2,047
  • 2
  • 15
  • 22
111
votes
6 answers

How to loop over a Class attributes in Java?

How can I loop over a class attributes in java dynamically. For eg : public class MyClass{ private type1 att1; private type2 att2; ... public void function(){ for(var in MyClass.Attributes){ …
Zakaria
  • 1,675
  • 4
  • 21
  • 23
110
votes
14 answers

Can a 'for' loop inside of a 'for' loop use the same counter variable name?

Can I use the same counter variable for a for loop inside of a for loop? Or will the variables affect each other? Should the following code use a different variable for the second loop, such as j, or is i fine? for(int i = 0; i < 10; i++) { …
Uclydde
  • 1,414
  • 3
  • 16
  • 33
109
votes
8 answers

Looping through alphabets in Bash

I want to mv all the files starting with 'x' to directory 'x'; something like: mv path1/x*.ext path2/x and do it for all alphabet letters a, ..., z How can I write a bash script which makes 'x' loops through the alphabet?
behzad.nouri
  • 74,723
  • 18
  • 126
  • 124
109
votes
9 answers

Rails: fields_for with index?

Is there a method (or way to pull off similar functionality) to do a fields_for_with_index? Example: <% f.fields_for_with_index :questions do |builder, index| %> <%= render 'some_form', :f => builder, :i => index %> <% end %> That partial…
Shpigford
  • 24,748
  • 58
  • 163
  • 252
109
votes
4 answers

How can I return something early from a block?

If I wanted to do something like this: collection.each do |i| return nil if i == 3 ..many lines of code here.. end How would I get that effect? I know I could just wrap everything inside the block in a big if statement, but I'd like to avoid…
ryeguy
  • 65,519
  • 58
  • 198
  • 260
106
votes
1 answer

Avoiding memory leaks with Scalaz 7 zipWithIndex/group enumeratees

Background As noted in this question, I'm using Scalaz 7 iteratees to process a large (i.e., unbounded) stream of data in constant heap space. My code looks like this: type ErrorOrT[M[+_], A] = EitherT[M, Throwable, A] type ErrorOr[A] = ErrorOrT[IO,…
Aaron Novstrup
  • 20,967
  • 7
  • 70
  • 108
105
votes
3 answers

For Loop on Lua

My assignment is how to do a for loop. I have figured it out in terms of numbers but cannot figure it out in terms of names. I would like to create a for loop that runs down a list of names. Following is what I have so far: names = {'John', 'Joe',…
SamYoungNY
  • 6,444
  • 6
  • 26
  • 43
104
votes
6 answers

VB.NET - How to move to next item a For Each Loop?

Is there a statment like Exit For, except instead of exiting the loop it just moves to the next item. For example: For Each I As Item In Items If I = x Then ' Move to next item End If ' Do something Next I know could simply…
Sean Taylor
  • 4,948
  • 8
  • 25
  • 27