Home > Web Front-end > JS Tutorial > body text

Several ways to use while loop to calculate and print the sum of even numbers from 2 to 100

一个新手
Release: 2017-09-21 09:40:13
Original
4227 people have browsed it

Use while loop to calculate and print the sum of even numbers from 2 to 100 (three methods)

1. Loop—while
Syntax: while (condition) {

//Loop body-loop operation//Update loop conditions++/--;

}

##2.continue
Function: Terminate the execution of this cycle and continue the next cycle

<p style="margin-bottom: 7px;"><!doctype html><br/><html lang="en"><br/> <head><br/>	 <meta charset="UTF-8"><br/>     <title>Document</title><br/>	 <link rel="stylesheet" style="text/css" href=""><br/>	 <style><br/><br/><br/>	 </style><br/> </head><br/> <body><br/>	 <script><br/>		计算打印2——100的偶数和<br/>	// 方法1:<br/>		function sumOs(){<br/>			var os=0;<br/>			var i=2;<br/>			while(i<=100){<br/>				os+=i;<br/>				i+=2;<br/>			}<br/>		console.log(os);<br/>		}<br/>		sumOs();<br/>	<br/>	//方法2:<br/>		function sumOs(){<br/>			var os=0;<br/>			var i=1;<br/>			while(i<=100){<br/>				if(i%2==0){<br/>					os+=i;<br/>				}<br/>			i++;<br/>			}<br/>		console.log(os);<br/>		}<br/>		sumOs();<br/>	<br/>	//方法3:<br/>		function sumOs(){<br/>			var os = 0;<br/>			var i = 1;<br/>			while(i<=100){<br/>					if(i%2==1){<br/>						i++;<br/>						continue;<br/>					}<br/>					os += i;<br/>					i++;<br/>				}<br/>				console.log(os);<br/>			}<br/>		sumOs();<br/><br/><br/>	//扩展:循环从弹窗中录入信息,并且打印,直到输入exit为止<br/>		function printMsg(){<br/>			while(true){<br/>				var msg=prompt("请输入一个字段啊");<br/>				if(msg=="exit"){<br/>					break;<br/>				}else{<br/>					console.log(msg);<br/>				}<br/>			}<br/>		}<br/>		printMsg();<br/>	</script><br/> </body><br/></html><br/></p>
Copy after login

The above is the detailed content of Several ways to use while loop to calculate and print the sum of even numbers from 2 to 100. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template