logo

Programming Languages - Loops

Last Updated: 2024-01-21

C++

for (int i = 0; i < items_size; ++i) {
  cout << items[i] << endl;
}

for (int i : items) {
  cout << i << endl;
}

Use const reference:

std::string words[] = { "a", "b", "c", "d" };
for (const std::string& word : words) {
  // ...
}

Loop through maps:

std::map<std::string, int> numbers = {{"a", 0}, {"b", 1}, {"c", 2}};
for (const auto& p : numbers) {
  cout << p.first << ": " << p.second;
}

for (const auto& [key, value] : my_map) {
  printf("%f\n", value);
}

Mutable repeated fields:

for (auto& message : *foo.mutable_values()) {
  message.set_field(true);
}

The traditional while loop, looks the same in C++ and Java.

while (condition) {
  // ...
}

do {
  // ...
} while (condition)

Go

The for loop is the only looping construct in Go.

Note: Unlike other languages like C, Java, or JavaScript there are no parentheses surrounding the three components of the for statement and the braces { } are always required.

sum := 0
for i := 0; i < 10; i++ {
  sum += i
}

Equivalent to a while loop.

sum := 1
for sum < 1000 {
  sum += sum
}

Infinit loop:

for {
  // ...s
}

Range over Channels. for loop exits when the channel is closed.

ch := make(chan string, 2)
// ...
for item := range ch {
  // ...
}

Rust

let items = [1, 2, 3];

for i in 0..items.len() {
    println!("{}", items[i]);
}

for i in &items {
    println!("{}", i);
}
loop {
  if (condition) {
    break;
  }
}

Java

for (Integer k : list) {
    // ...
}
int len = list.size();
for (int i = 0; i < len; i++) {
    Integer k = list.get(i);
    // ...
}

While loop

while (condition) {
  // ...
}

do {
  // ...
} while (condition)

JavaScript

Use for ... in to loop through the index, and for ... of to loop through the values.

const strings = ['str1', 'str2', 'str3'];

for (let i in strings) {
  console.log(i);
}
// result:
// 0
// 1
// 2

for (let s of strings) {
  console.log(s);
}
// result:
// str1
// str2
// str3

Python

Loop In A Range

equivalent to Java's for (int i = 0; i < 5; i++) {}

>>> for i in range(1, 5):
...     print(i)
...
1
2
3
4

With step:

>>> for i in range(1, 10, 2):
...     print(i)
...
1
3
5
7
9

enumerate

for i in range(len(flavor_list)):
    flavor = flavor_list[i]
    print('%d: %s' % (i + 1, flavor))

for i, flavor in enumerate(flavor_list):
    print('%d: %s' % (i + 1, flavor))

Loop In A Collection

  • for item in s: Iterate over the items of s
  • for item in sorted(s): Iterate over the items of s in order
  • for item in set(s): Iterate over unique elements of s
  • for item in reversed(s): Iterate over elements of s in reverse
  • for item in set(s).difference(t): Iterate over elements of s not in t
  • for item in random.shuffle(s): Iterate over elements of s in random order

Bash

As one-liner:

$ for i in {1..5}; do echo "$i"; done
1
2
3
4
5