# Loops

Last update : February 11th, 2022

A loop in programming is used to iterate over items. It allows you to repeat instruction lines several times. For instance, if we want to double each item in an array, it can be possible with just one line of code. Let's see several loops in Python, JavaScript, C, and C++.

### Simple for loop

The for loop has 4 parts :

• initialization
• condition
• increment
• statement

There are all expressions (any unit of code that can be evaluated to a value).

The initialization determines the start of the counter. It also allows the creation of variables. The counter(s) generally starts at zero, but it can be 1, 2, etc.

The condition is the step where the expression is evaluated. It allows the execution as long as the condition is true. This means that the loop stops when the condition is false.

The increment determines how the loop control is incremented each time the loop repeats successfully. It could be just one step ( + 1) or two steps, divided, and so on. There are shortcuts (i++ for instance).

The statement (in the body) executes (instruction to perform a specific action).

#### Two times more

The number of each fruit column is multiplied by two. There are three columns of fruits, first column one fruit, second column two fruits, and third column three fruits. A machine with x2 appears below each column to indicate that the machine will multiply each column by two, and this for three times because there are three columns. In the last comic strip, we find the columns of fruits doubled.

#### Code

python
1fruits = [1, 2, 3]
2
3for x in fruits:
4  print(x * 2)

Time complexity : linear

array length : 3

Before

• 1
• 2
• 3
array length : 3

Result

• 2
• 4
• 6

#### parameters

As said earlier the loop can start at 0 but also 1 and so on. So now the loop starts at the second index (1) and as a result we get 2 items instead of 3.

#### Code

javascript
1const fruits = [1, 2, 3];
2
3for (let i = 1; i < fruits.length; i++) {
4   console.log(fruits[i] * 2);
5}

array length : 3

Before

• 1
• 2
• 3
array length : 2

Result

• 4
• 6

#### decrementation

We can also decrement the counter (- 1). For that, we need to be careful about the condition expression, even the initialization part. For example, we could swap items. Here we will also stop the loop at a specific index (2). For the initialization, the number has to be bigger than the condition.

#### Let's switch and leave!

We find a lineage of different fruits. Two steps are performed, the change of direction and the removal of a fruit. The change of direction corresponds to the decrement, and we stop the inversion just before reaching the pineapple, so it is deleted.

#### Code

javascript
1const fruits = [1, 2, 3, 4, 5];
2
3for (let i = fruits.length; i >= 2; i--) {
4  console.log(i);
5}

array length : 5

Before

• 1
• 2
• 3
• 4
• 5
array length : 4

Result

• 5
• 4
• 3
• 2

#### nested

A nested loop can be handy to compute two nested arrays. First, we must think in terms of the parent-child relationship. The parent's loop is executed first, then the child. The child restarts every time, but the parent continues when the child's condition is false.

The "j < i" is important, "j" is the child, "i" the parent. The "j" always restarts, the "i" continues its path. As a result, we have several groups that correspond to the parent.

We can see that the groups are getting bigger as we go along.

Finally, in the second box of the result, which corresponds to the children, we can observe that the child runs from zero each time and that the end of its cycle depends on its parent.

#### Boarding

There are several cars that must accommodate passengers. But there are specific conditions. At each departure, we add one more passenger. The wagons correspond to the parents and the passengers (the fruits), to the children. At each departure the number of cars increases. So for the first departure, we have one wagon. For the second departure, we have two wagons, and so on. So there are two departures in this cartoon.

#### Code

javascript
1const cars = [1, 2, 3, 4, 5];
2
3for (let i = 0; i < cars.length; i++) {
4  for (let j = 0; j < i; j++) {
5    console.log(i, j);
6  }
7  console.log('');
8}
9

array length : 5

Before

• 1
• 2
• 3
• 4
• 5

Result

• 1
• 0
• 2
• 0
• 2
• 1
• 3
• 0
• 3
• 1
• 3
• 2
• 4
• 0
• 4
• 1
• 4
• 2
• 4
• 3

### While

This is a smaller loop that runs as long as the condition is true. Always put a condition to avoid an infinite loop.

#### Code

python
1fruits = [1, 2, 3]
2i = 0
3
4while i < len(fruits):
5  print(fruits[i] * 2)
6  i += 1

array length : 3

Before

• 1
• 2
• 3
array length : 3

Result

• 2
• 4
• 6

### Do while

Same as while but we execute first, the test is done at the exit of the loop.

#### Code

javascript
1const fruits = [1, 2, 3];
2let i = 0;
3
4do {
5  console.log(fruits[i] * 2);
6  i++;
7}
8while (i < fruits.length);

array length : 3

Before

• 1
• 2
• 3
array length : 3

Result

• 2
• 4
• 6

### Break

The break statement is used to stop the loop. However, it is not recommended to use it.

For example, we can stop the loop if the second element of the array is equal to 2.

#### Code

python
1fruits = [1, 2, 3]
2i = 0
3
4while i < len(fruits):
5    if i == 2:
6        break
7    i += 1
8print(i)

#### Data

array length : 3

Before

• 1
• 2
• 3
array length : 1

Result

• 2

As we have seen, loops are very useful in programming. They are built-in loops, but it's possible to use loops that are easier to use but slower. Depending on the type of data, you will have to be careful to avoid infinite loops.