# Instructions break and continue in loop statements. Examples of tasks solving

### Contents

- 1. Instructions break and continue. The purpose
- 2. Examples of solving tasks using the break statement
- 3. Examples of solving tasks using the continue statement
- Related topics

**Search other resources:**

##### 1. Instructions break and continue. The purpose

JavaScript provides tools to interrupt the current iteration of a loop. These tools include instructions (operators):

- break – performs an unconditional exit from the loop;
- continue – moves to the next iteration of the loop. All statements not yet executed in the current iteration are skipped.

As a rule, the break and continue statements are used in combination with the conditional branch operator, if, depending on the fulfillment of some condition, the current iteration must be interrupted.

The break and continue statements provide a wide range of possibilities for solving problems using loops.

Figure 1. Using the break statement in different types of loops in combination with the if statement: a) – for loop; b) – while loop; c) – do-while loop

Figure 2. Using the continue statement in different types of loops: a) – for loop;

b) – while loop; c) – do-while loop

### ⇑

##### 2. Examples of solving tasks using the break statement

##### 2.1. Searching for an element in an array

**Task.**

An array of numbers has been specified. Implement searching for an element in the array. The array of numbers and element is entered from the keyboard.

**Solution.**

The text of the JavaScript program that solves this task.

// The break statement // Search for an element in an array. // 1. Array creation var A = [] // 1.1. Enter the number of elements in the array var n = prompt("Input n:") // 1.2. Enter the elements of an array using for loop. for (var i = 0; i<n; i++) { A[i] = prompt("Input A[" + i + "]:") } // 2. Output the entered array for control, form the array as a string var s = "" for (var i = 0; i < A.length; i++) { s = s + A[i] + " "; } alert("A = [ " + s + " ]") // 3. Input the item var item = prompt("Input item:") // 4. Loop searching for an element in an array var pos = -1 // the position of the element in the array for (var i = 0; i < n; i++) { if (item == A[i]) { // if the element is found, then remember the position and exit the loop, // further search does not make sense pos = i break; // exit from the loop } } // 5. Display the result if (pos != -1) alert("Item " + item + " is in the array A at position " + pos) else alert("Item is not in the array A")

In step 4 of the program, each element of the array is compared with the desired element. Once the desired element is found, further iterations are meaningless, since the element has already been found. Here you need to start from the loop, which was done using the break statement.

### ⇑

##### 2.2. Calculation of the sum with a given precision

**Task.**

Calculate with a given accuracy the value of the sum

**Solution**

When the task is performed, an allegedly eternal cycle is organized. The loop calculates the current value of the expression and appends it to the summ. It also remembers the value of the sum, which was at the preliminary iteration of the loop. As soon as the difference between the previous and next values is less than some specified precision *ε* (*ε* > 0), the loop is exited using the break statement.

The text of the program that solves this task is as follows.

// The break statement // Task. Calculate the sum of values 1/i!, where i = 1, 2, 3, ... // 1. Declare variables var epsilon // direct precision, e.g. 0.01 or 0.000001 var sum // the required summ var prev_sum // previous sum value var i // counter of the current iteration var fact // fact = i! // 2. Enter the precision of the sum calculation epsilon = prompt("Input epsilon") // 3. Sum calculation loop sum = 0 prev_sum = 0 fact = 1 i = 1 while (true) { // supposedly eternal cycle sum += 1/fact // Checking the change of the current value of the sum, // if the accuracy of the calculation is reached, then exit from the loop if (Math.abs(sum-prev_sum)<epsilon) break i++ fact = fact*i prev_sum = sum } // 4. Display the sum alert("sum = " + sum)

### ⇑

##### 2.3. Determine if the digits of a number form a non-decreasing sequence

**Task.** A number is given. Determine if the digits of a number form a non-decreasing sequence. For example, for the number 23344 the answer should be “Yes”.

**Solution.**

When defining a non-decreasing sequence, it is sufficient that between two adjacent digits of a number, the first digit (of the highest order) is not greater than (<=) the second digit. As soon as it turns out that the first digit is greater than the second, the exit from the cyclic process will immediately take place using the break statement.

The text of the program that solves this task is as follows

// The break statement // Determine if the digits of a number form a non-decreasing sequence // 1. Input number var num = prompt("Input number:") // 2. Checking if a number has at least two digits if (num >= 10) { // 3. Non-decreasing sequence definition loop var t = num, t1, t2 var f_non_decr // result flag // At the beginning, assume that the sequence is non-decreasing f_non_decr = true do { t1 = t%10 // get the last number t2 = parseInt((t%100)/10) // take the penultimate number // Compare numbers if (t2 > t1) { // if the sequence is non-decreasing, then exit from the loop // using the break statement f_non_decr = false break; } t = parseInt(t/10) } while (t > 0) // 4. Outputting the result based on the f_non_decr flag if (f_non_decr) alert("The sequence is nondecreasing") else alert("The sequence is not nondecreasing") } else { alert("Incorrect input") }

### ⇑

##### 3. Examples of solving tasks using the continue statement

##### 3.1. Calculate the sum of array elements at even positions

**Task.** An array of numbers has been specified. Calculate the sum of array elements placed at even positions (0, 2, 4, 6, …).

**Solution.**

In a cyclic process, when determining the amount, odd positions are skipped using the continue statement.

// The continue statement // Task. Calculate the sum of elements lying on paired positions // 1. Declare an array and fill it with values var A = [ 2, 8, -1, 3, 9, 12, 0, 15, 18 ] // 2. Sum loop var sum = 0 for (var i=0; i<A.length; i++) { if (i%2==1) // if the position is odd, continue; // then go to the next iteration of the loop sum += A[i] } // 3. Display the sum alert("sum = " + sum)

### ⇑

##### 3.2. Create a list of strings according to a condition

**Task.** Strings are entered from the keyboard. The end of input is an empty string. Based on the entered strings, create a list of strings with a maximum length of 5 characters.

**Solution.**

A loop with a do-while postcondition is best for organizing string input from the keyboard, since you first need to get the string, and then process it (process the condition).

This loop adds strings to the array. If the length of the added string is more than 5 characters, then the next iteration of the loop is passed by the continue statement, that is, the string is not added to the array.

// The continue statement // Task. Create list of strings according to condition // 1. Declare variables var AS = [] var s var i // 2. String input loop, AS array created at the same time i=0 do { // 2.1. Input a string s = prompt("Enter string:") // 2.2. Processing a string according to a condition if (s.length > 5) // if string length > 5, continue; // then go to the next iteration // 2.3. Add string to AS array AS[i] = s i++ } while (s != "") // 3. Display the array var resStr = "[ " for (var i=0; i<AS.length; i++) resStr += AS[i] + " "; resStr += " ]" alert("AS = " + resStr)

### ⇑

##### 3.3. Calculate the sum of numbers in a given range

**Task.**

Numbers are entered from the keyboard. End of input – number 0. Calculate the sum of numbers in the range [5; 10].

**Solution.**

// The continue statement // Task. Calculate the sum of the entered numbers in the range [5; ten] // 1. Declare variables var num // number to be entered var sum // summ // 2. Number entry loop and sum calculation sum = 0 do { num = prompt("Enter number:") if ((num<5)||(num>10)) continue; sum = sum + parseInt(num) } while (num!=0) // 3. Display the result alert("sum = " + sum)

### ⇑

### Related topics

- The concept of a loop. Loop statements for, while, do-while
- The for-in loop. Nested loops. Eternal loop

### ⇑