본문 바로가기

Javascript

while문 으로 0에서 n까지 합/do-while문

while문 으로 0에서 n까지 합

아래에 코드있어요!

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h3>while문으로 0에서 n까지 합</h3><hr>
    <script>
        var n = prompt("0보다 큰 정수를 입력하세요.","1");
        n = parseInt(n) //문자열이 정수로 변경
        i = 0; sum = 0;
        while(i<=n){
            sum+=i;
            i++;
        }
        document.writeln("0에서 "+n+"까지의 합은" +sum);
    </script>
 
</body>
</html>
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

do-while문

 

아래에 코드 있어요!

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h3>do-while문</h3><hr>
    <script>
        //1에서 10까지 힙을 do-while문 구현
        sum=0;
        i=1;
        do{
            sum+=i;
            i++
        }while(i<11);
        document.writeln("sum : "+ sum);
    </script>
</body>
</html>
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs