# The concept of a loop. Loop statements for, while, do-while. Examples

### Contents

- 1. The concept of a loop process. Loop. Types of loop statements in JavaScript
- 2. Loop for. Execution syntax. The work of the for loop
- 3. Loop while
- 4. Loop do-while
- Related topics

**Search other resources:**

##### 1. The concept of a loop process. Loop. Types of loop statements in JavaScript

When writing programs of varying complexity, there is often a need to repeatedly perform the same type of operations. Loop statements are used to perform frequently repeated operations in JavaScript.

There are the following types of loop statements:

- for – loop with a parameter;
- for-in – loop of moving through objects;
- while – loop with precondition;
- do-while – loop with postcondition.

The programmer chooses which of the cycles to apply in a particular case. Loops for, while, do-while can replace each other.

### ⇑

##### 2. Loop for. Execution syntax. The work of the for loop

The implementation of the for loop in JavaScript is very similar to the same loop in C++, C#, Java. In general, the for loop can be represented as follows:

for(init_expr;cond_expr;modification) {// Loop body// ...}

here

- init_expr – loop counter initialization expression. There can be several initialization expressions, in which case each expression is separated by a comma;
- cond_expr – conditional expression;
- modification – one or more loop counter modification expressions. The loop counter can update its value in both descending and ascending order.

Any of the init_expr, cond_expr, modification parts may be missing.

The for loop works according to the following algorithm.

- First, one or more init_expr initialization expressions are executed.
- The conditional expression cond_expr is checked. If the result of checking the conditional expression is true (cond_expr = true), the transition to step 3 occurs. If cond_expr=false, then the loop exits, that is, the transition to step 6.
- Execution of one iteration of the loop body.
- After one iteration of the body of the loop, control is transferred to the modification operator. Here the value of the loop counter is changed.
- Go to step 2 – check condition.
- End of cycle execution.

### ⇑

##### 2.1. An example of calculating the arithmetic mean of array elements

The example calculates the arithmetic mean of the elements of an array of floating point numbers. To get the number of elements in an array, use the length property of that array.

// Loop for// Calculate the average of array elements// 1. The given arrayvarA = [2.8, 3.5, 1.4, 3.2, 1.7];// 2. Declare variablesvaravg = 0// the result is the arithmetic average.// 3. Loop for calculating the sum of array elements,// here A.length - number of array elementsfor(vari = 0; i < A.length; i++) avg += A[i]// 4. Calculate the averageavg = avg / A.length// 5. Display the resultconsole.log("avg = ", avg)

Result

avg = 2.5199999999999996

### ⇑

##### 2.2. An example of the formation of a Fibonacci series for a given maximum value

// Loop for// Form a Fibonacci series for a given n// 1. Given nvarn = 50// 2. Declare additional variablesvart1, t2, t3vars = ""// resulting string formed from numbers// 3. Calculation of elements of the Fibonacci series.// The resulting string is formedt1 = 1 t2 = 1 t3 = t1 + t2 s = s + t1 +" "+ t2 +" "for(t1 = 1, t2 = 1; t3 <= n;) { t3 = t1 + t2; s = s + t3 +" "; t1 = t2; t2 = t3; }// 4. Display the resulting string sconsole.log(s)

Result

1 1 2 3 5 8 13 21 34 55

### ⇑

##### 2.3. Example of function tabulation y = sin(x)

The example shows how to use a for loop to create data based on the results of tabulating the sin(x) function.

// Function tabulation y = sin(x)// in the range [a; b] in step h.// 1. Given a, b - range and step h = 0.1vara = 0, b = 2, h = 0.1;varx, y;// 2. Cyclic tabulation process with output to the screen of the resultfor(vart = a; t <= b; t += h) {// Round result to 2 decimal placesx = Number.parseFloat(t).toFixed(2); y = Number.parseFloat(Math.sin(t)).toFixed(2);// Display the result on the screenconsole.log("x = ", x," y = ", y); }

Result

x = 0.00 y = 0.00 x = 0.10 y = 0.10 x = 0.20 y = 0.20 x = 0.30 y = 0.30 x = 0.40 y = 0.39 x = 0.50 y = 0.48 x = 0.60 y = 0.56 x = 0.70 y = 0.64 x = 0.80 y = 0.72 x = 0.90 y = 0.78 x = 1.00 y = 0.84 x = 1.10 y = 0.89 x = 1.20 y = 0.93 x = 1.30 y = 0.96 x = 1.40 y = 0.99 x = 1.50 y = 1.00 x = 1.60 y = 1.00 x = 1.70 y = 0.99 x = 1.80 y = 0.97 x = 1.90 y = 0.95

### ⇑

##### 3. Loop while

The while loop is called a precondition loop. This means that for the execution of the first and each subsequent iteration of the loop, the condition for executing the loop is first checked.

The general form of the while loop operator is the same as in C++, C#, Java:

while(condition) {// Loop body// ...}

here

- condition – some conditional expression. The loop body is iterated over iteration if condition = true. If condition becomes false when checking the condition, the loop exits.

### ⇑

##### 3.1. An example of determining the maximum value in an array

// Loop while// Finding the maximum in an array// 1. The array is specifiedvarA = [2, 3, 8, -4, 9, 6, 7]// 2. Set maximum to the first element of an arrayvarmax = A[0]// 3. Finding loopvari = 1while(i < A.length) {if(max < A[i]) max = A[i]; i++; }// 4. Display the resultconsole.log("max = ", max)

Result

max = 9

### ⇑

##### 3.2. Finding a number according to a condition

**Task****. **

A number ** a** is given for which the condition is satisfied

1 < a ≤ 1.5

Among the numbers

1+1/2, 1+1/3, 1+1/4, ...

find the first one that is less than the number ** a**.

**Solution.**

// Loop while// Finding the first number less than a// in a series of numbers: 1+1/2, 1+1/3, 1+1/4,...// 1. The number a is specifiedvara = 1.05;// Declare additional variablesvarres, t t = 2; res = 1 + 1 / t;while(res >= a) { t = t + 1; res = 1 + 1 / t; } console.log("t = ", t); console.log("res = ", res);

Result

t = 21 res = 1.0476190476190477

### ⇑

##### 3.3. Processing strings in a while loop. Example

**Task****.**

Text is given. Find the position of the first occurrence of the ‘+’ character in this text.

**Solution****.**

// Processing text in a while loop.// Find position of first occurrence of '+' character in text// 1. Read the textvarstr = prompt("Input text:")// 2. Position determination cyclevarpos;// result - searching positionpos = 0while(str[pos]!='+') pos++;// 3. Display the resultalert("Position = "+ pos)

### ⇑

##### 4. Loop do-while

A do-while loop is also called a postcondition loop. This means that the body of the loop comes first, then the condition is checked. Thus, the loop body is executed at least once. If we consider the for and while loops, then there may be situations when the body of these loops will not be executed even once. This is the main difference between the do-while loop and the for, while loops.

The general form of declaring a do-while loop in JavaScript is the same as in C++, C#, Java:

do{// Loop body// ...}while(condition);

here

- condition – some condition. The loop body is executed if condition=true. As soon as the value of condition becomes false, the loop exits and moves to the next statement.

In some cases, the do-while loop feature results in more descriptive code. An example of such a case could be receiving data from the keyboard and processing it depending on the situation. If you use for or while statements, then you can not do without re-call the input line or enter additional flags that determine the first iteration step in the loop. The use of the do-while loop will not cause extra lines of code to solve the problem correctly (see Example 4.1).

### ⇑

##### 4.1. Data processing during input. An example of calculating the sum for a sequence of entered numbers

The do-while loop organizes the input of numbers from the keyboard by calling the dialog box with the prompt() function. The end of the input is the number 0. As a result, the sum of the entered numbers is calculated.

//Loopdo-while// Processing of data during input.// Given a sequence of numbers that ends in zero.// Calculate the sum of the entered numbers.// 1.Declare variablesvarnum// the number that will be entered from the keyboardvarsum = 0.0//calculated sum// 2.The loop of calculationdo{// Display a number entry windownum = prompt("Enter number: ",'0'); sum += parseFloat(num); }while(num!=0);// 3.Display the resultdocument.write("sum = "+ sum)

### ⇑

##### 4.2. Calculating the maximum digit of a number

**Task****. **

Given a natural number. Calculate the maximum digit of this number.

**Solution****.**

// Loop do-while// Calculate the maximum digit of a number entered from the keyboard// 1. Declare variablesvarnum// given numbervarmax// maximum digit of a number// 2. Input datanum = parseInt(prompt("Enter number: "))// 3. Calculating the maximum digit of a number - do-while loopmax = num % 10// get the last digitdo{if(max<num%10) max = num%10 num = parseInt(num/10) }while(num>0)// 4. Display the resultalert("max = "+ max)

### ⇑

##### 4.3. String processing. Replacing characters in text

**Task****. **In the given text, replace all **‘+’** characters with **‘-‘** characters. Use a do-while loop to solve.

**Solution****.**

When solving this problem, it should be taken into account that strings are immutable sequences. Therefore, it will not work to directly replace the character in the original text. In this task, a new (different) text is formed, which then replaces the original text.

// Processing text in a do-while loop.// In the given text, replace all '+' characters with '-' characters.// 1. Input textvartext = prompt("Input text:")// 2. Replacement cyclevari = 0// index of the processed character in the textvartext2 =""// additional textdo{// Handling the character text[i]if(text[i] =='+') text2 = text2 +"-"elsetext2 = text2 + text[i]// Increase counteri++ }while(i < text.length)// 3. Replace original texttext = text2// 4. Display the resultdocument.write("text = "+ text)

### ⇑

### Related topics

### ⇑