Loop

Goals

In programming, repetition is an important part in conditional branching. In today’s lesson we will learn about repetition in JavaScript. We will also look to understand what blocks and statements are with respect to repetition

  • Understanding sentences and blocks.
  • Understanding the behavior of the while statement. Writing while statements correctly.
  • Understanding the behavior of the for statement. Writing a for statement correctly.   
  • Rewriting the iteration written in the while statement with the for statement.   
  • Rewriting the iteration written in the for statement with the while statement. 
  • Understanding the behavior of repeated use of the continue statement.
  • Understanding the behavior of iteration using a break statement.

Sentences and Blocks

Last time we learned that the if statement uses specific syntax. In this example of an if statement, the parts surrounded by curly brackets “{” and “}” are executed or not, depending on the conditions of the if and else statements that surround it.

if (condition 1) {
/* *
This block is executed when condition 1 is satisfied
*/
} else if (condition 2) {
/* *
This block is executed when condition 1 is not satisfied and condition 2 is satisfied
*/
} else if (condition 3) {
/* * This block is executed when conditions 1-2 are not satisfied and condition 3 is satisfied */ ...
} else if (condition n) {
/* * This block is only executed when conditions 1-n-1 are not satisfied and condition n is satisfied */
} else {
/* *
This block is executed when none of the above conditions are satisfied
*/
}

Actually, however, this expression is not necessarily correct. In JavaScript, the syntax of an if statement is as follows:

if (condition 1)
// This block is executed when condition 1 is satisfied
else if (condition 2)
// This block is executed when condition 1 is not satisfied and condition 2 is satisfied
else if (condition 3)
// This block is executed when conditions 1-2 are not satisfied and condition 3 is satisfied
...
else if (condition n)
// This block is only executed when conditions 1-n-1 are not satisfied and condition n is satisfied
else
// This block is executed when none of the above conditions are satisfied

In JavaScript, it is given that parts enclosed in curly brackets “{}” are treated as one sentence. Therefore, it is possible to write conditional statements like the ones shown at the beginning. Conversely, the if statement can be written as follows without using curly braces. In this example, if the variable n is an even number, “even number” is displayed, otherwise a message “it is odd number” is displayed.

if (n % 2 == 0)
 alert("Even Number!");
else alert("Odd Number");

Loops

while statement

While statements are used as a control statements for basic repetition. The while statement repeats the process so long as a certain condition is satisfied. The format is as follows.

while (condition)
 When the condition is satisfied, the loop is executed

Of course, you can write as follows.

while (condition) {
 /* *
  <span id="result_box" class="short_text" lang="en" tabindex="-1">While the condition is satisfied, this block is executed</span>
 */
}

The format of a while loop is very similar to a simple if statement. In fact, the expression written at the “condition” area of the while loop, is the same as the condition expression used for the if statement.

In the while statement, the condition is first evaluated, and when the condition is satisfied, the block enclosed in curly brackets is executed. Up till this point, the behavior is the same as the if statement. However, when the execution of the block enclosed in curly brackets is completed, instead of executing the closing brace, execution returns to the condition evaluation again. This is repeated until the condition is proven false.

The following is a program that starts a counter from 1 and sequentially displays the value doubled. This process of doubling the value keeps going on until the counter reaches a value of 100.

 

var n = 1;
while (n < 100) {
 alert(n);
 n = n * 2; 
} 


In this program, we first set n to 1 and then enter the while statement. In the while statement, if n is smaller than 100, first display that number in a popup, then double n to prepare for the next round.

When executing the while statement for the first time, n is 1, but at the end of the while block, n is doubled to 2 by the sentence "n = n * 2". Since n is smaller than 2, the block enclosed in curly braces of the while sentence is executed again. After displaying 2, "n = n * 2" is executed again and n becomes 4. After that, the same part is repeated until n reaches 128. When n reaches 128, since the condition of the while statement on the second line is no longer established, the program exits from the block after the while statement.

If you make a mistake in the repeating condition, the same thing will be repeated endlessly, sometimes resulting in a state in which the program does not end. Such a state is expressed as "infinite loop". When it comes to an infinite loop state, the browser may stop responding. In such a case, the browser must be terminated and restarted. When you press three buttons "command" "option" and "esc" on the keyboard at the same time (For MAC),  a "Force Quit Application" screen opens, where you must specify the browser and force quit.

Note that if you open the same page after rebooting the browser, you will also enter the infinite loop, so you must modify the page before opening the page again.

do-while statement

Do-while statements behave similarly to while statements, but where the conditions are evaluated is different. The format of the do-while statement is shown below.

do once and、
<span id="result_box" class="short_text" lang="en" tabindex="-1"><span class="">While the condition is satisfied, the statement is repeated</span></span>
while (condition);

See the flowchart below. This is a flow chart of the do-while statement. Compared to the while statement, we see that the part evaluating the condition is processed before the condition is evaluated. Therefore, if you use a do-while statement, it is possible to create a loop where processing is executed at least once.

Do-while statements are not frequently used much as compared to while statements. This is because there are not many situations in which algorithms must be executed at least once.

for statements

When you use iteration, you often use certain variables as counters. A for statement is useful in such a case. The for statement provides such a syntax that it is possible to write three statements for each of the three variables:
A. variable initialization
B. condition
C. counter operation

These would have to be written separately in the while statement, but can be written in one line. See the syntax below; the two bits of code are interchangeable.

Example using a while statement

A.Initialization
while (B.condition) {
/*
* When the condition is satisfied, this block is executed
*/
C.A counter is manipulated;
} 

Example using a for statement

for (A.initialization; B.condition; C.counter change)
This block is executed so long as the condition is satisfied

Writing each one as a concrete example will be as follows. Example using a while statement

 var i = 0;
 while (i < 10) {
  alert("This is repeated。");
  i++; 
 } 

Example using a for statement

for (var i=0; i<10; i++)
 alert("This is repeated"); 

This is to execute the processing block ten times from i = 0 to i = 9. In this example, variables are defined at the same time using var in the "A. initialization" part of the for statement, but this may be done outside the iteration as shown below.

 

var i;
 for (i=0; i<10; i++) { 
/** This block is executed when the condition is satisfied*/
} 

In addition, although there is "C. counter operation" in the for statement syntax, it is also possible to write an assignment statement here. For example, if you want to advance the counter to 0, 2, 4, 6, 8 you can write:

 for (var i=0; i<10; i=i+2)
 {
 /*
  * This block is repeated so long as the condition is satisfied 
  */ 
 } 

"i = i + 2" has the same meaning in "i + = 2".

It is also possible to reduce the counter. If you want to do like 10, 8, 6, 4, 2, write as follows. In this example as well, "i = i - 2" can be rewritten as "i - = 2".

 for (var i=10; i>0; i=i-2) {
 /*
  * This block is executed so long as the condition is satisfied
  */
 }
 

Iteration Control

If you are using repeat, you may want to stop running through the loop at some point, or you may want to go to the next round right now. For such a case JavaScript provides a break statement and a continue statement.

break statement

If you want to stop the iteration halfway, you can escape from iteration regardless of the condition by using the break statement.

See the next program. This program inputs ten characters "male" or "female" and displays the number of times each input was made.

 

 var male = 0;
 var female = 0;
 for (var i=0; i<10; i++) {
  var sex = prompt("Enter Male or Female");
  if (sex == "Male")
   male = male + 1;
  else
   female = female +1;
 } 
alert("Males" + male + " Females: " + female);
 


In this example, you must enter ten characters. How can we stop it in the middle? For example, to input the character string "end", to display the total so far, do as follows.

var male = 0;
var female = 0;
for (var i=0; i<10; i++) {
var sex = prompt("Enter Male or Female");
if (sex == "end")
break;
if (sex == "Male")
male = male + 1;
else
female = female +1;
}
alert("Males: " + male + " Females: " + female);


continue statement


In the above example, if you input a character string other than "man" "end", it will be counted as a female. Here, if you input a character string other than "male", "female" and want to end you need to prevent the counter from an unnecessary increment. To do that, there is a way to set one of the clauses of the if statement to an else if, but you can also do as follows.

 

var male = 0;
var female = 0;
for (var i=0; i<10; i++) {
var sex = prompt("Enter Male or Female");
if (sex == "end")
break;
if (sex != "Male" || sex != "Female")
continue;
if (sex == "Male")
male = male + 1;
else
female = female +1;
}
alert("Males: " + male + " Females: " + female);



In this example, when a character string which is not "male" or "female" is input by using the continue statement, it does not perform the counting operation and enters the next iteration. It should be noted that there is an if statement as well as a continue statement after the sentence that checks whether it is the character string "end" or not.
Conversely, even if the character string "end" is entered, it is neither "man" nor "woman", so it returns to the beginning of the iteration.

Exercise 4-1

Use a while statement to create a program that alerts you to only even numbers "0, 2, 4, 6, 8, 10" among the numbers from 0 to 10.

Exercise 4-2

Use a for statement to create a program that alerts you to odd numbers "1, 3, 5, 7, 9" among the numbers from 0 to 10.

Exercise 4-3


Try N times with the Monte Carlo method and create a program to calculate the Pi. However, let N = 100. In addition, the method of obtaining the circumference ratio by the basic Monte Carlo method is as follows.

Set m to 0.
Point at any point (x, y) in the 1 × 1 range.
If the distance from the origin of the point (SQRT (x 2 + y 2)) is 1 or less, 1 is added to m.
Repeat steps 2-3 N times.
The area of ​​the quarter circle is πr 2/4, and in the above case r = 1, so π can be found with 4 m / N


Exercise 4-4

In the above Monte Carlo method program, make it possible to enter the number of trials from the prompt.