Javascript flow control - while statement and do while statement exercise

1. The execution flow of the while statement

1. Determine whether the conditional statement is true, and true executes the following curly brackets

2. Only if the conditions are not met, the group will jump out

3. If there is no loop condition, there must be a jump out statement

	<script type="text/javascript">
		var num=1;
		while(num <101){
			console.log("1");
			num++;
		}
	</script>

2. The generation of an infinite loop

When your expression is always true, there is a jump out of the statement

	<script type="text/javascript">
		while(true ){
			console.log("11");
		}
	</script>

3. Practice

Exercise 1: The user inputs an integer n and calculates the sum of 1+2+..+n

	<script type="text/javascript">
 		//1. Define the variable
 		var sum=0;
 		//2. Receive the number entered by the user
 		var n=+(window.prompt("Please enter an integer"));
 		// 3. Define a variable to save the incremented number
 		var num=1;
 		//4. Loop through
 		while(num<=n){
 			console.log("sum="+sum+" "+"num="+num);
 			sum=sum +num;
 			num++;
 		}
 		alert(sum);
 	</script>

Exercise 2: Get the number of multiples of the input number within 100 and print, and count the number

	<script type="text/javascript">
 		//1. Define the variable
 		var count=1;
 		//2. Define the variable to save the incremented number
 		var num=0;
 		var n=+(window.prompt("input number")) ;
 		while(count<+100){
 			//3. Judgment
 			if(count%n====0){
 				console.log("count="+count);
 				num++; }
 //Number++
 count++;
 }
 console. log("num="+num);
 </script>				
												
					

3. Do-while statement (execute it once and execute it according to judgment)

	<script type="text/javascript">
		var num=20;
		do{
			console.log(num);//First output once
		}
		while(num<10)
	</script>










Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325642207&siteId=291194637
Recommended