[JS] 반복문 활용

sireal·2024년 2월 15일
0

Frontend

목록 보기
13/15

1부터 10까지의 합계

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script>

        // 1부터 10까지의 합계 : 55
        cnt = 0;
        sum = 0;
        while(cnt<= 10){
            sum += cnt;
            cnt++;
        }
        console.log(sum);

    </script>
</head>
<body>
    
</body>
</html>
      

위의 예제를 for문으로 변경

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script>

        // 1부터 10까지의 합계 : 55
        cnt = 0;
        sum = 0;
        while(cnt<= 10){
            sum += cnt;
            cnt++;
        }
        console.log(sum);

        // 위의 예제를 for문으로

        sum=0;
        for(cnt=0; cnt<=10; cnt++){
            sum += cnt;
        }
        console.log(sum);

    </script>
</head>
<body>
    
</body>
</html>

2의 10승을 구하기

Document
<script>

    // 2의 10승을 구하기
    cnt = 0;
    sum1 = 1;
    while(cnt<10){
        sum1 *= 2;
        cnt++;
    }
    console.log(sum1);

</script>

위의 예제를 do-while 문으로

  
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script>

        cnt = 0;
        sum1 = 1;
        
        do{
            sum1 *= 2;
            cnt++;
        }while(cnt<10);
        console.log(sum1);
                        
    </script>
</head>
<body>
    
</body>
</html>

위의 예제를 for문으로

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script>

        sum1=1;
        for(cnt=0; cnt<10; cnt++){
            sum1 *= 2
        }
        console.log(sum1);

    </script>
</head>
<body>
    
</body>
</html>
  

별 10개 출력하기

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script>
      
        // 별 10개 출력하기
        let cnt1 = 0;
        while(cnt1<10){
            console.log("*");
            cnt1 ++;
       	}

    </script>
</head>
<body>
    
</body>
</html>

위의 예제를 for문으로

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script>
      
        for(cnt = 0; cnt<10; cnt++){
            console.log("*");
        }
    </script>
</head>
<body>
    
</body>
</html>

0개의 댓글