JavaScript를 이용하여 구구단을 출력해보겠습니다.

 

1. for문을 이용하여 2~9단을 출력하는 방법

 

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>구구단</title>
    <script>
        for(var i = 2; i<=9; i++) {
            for(var j = 1; j<=9; j++) {
                document.write(i + " * " + j + " = " + (i*j), "<br>");
            }
        }
    </script>
</head>
<body>
    
</body>
</html>

 

이중 포문을 통해 2~9단까지 구현해보았습니다.

변수 i는 2~9단까지를 나타내는 변수, j는 1~9까지 곱해지는 변수로 설정했습니다.

for문 안에 있는 for문이 1~9까지 곱해지는게 끝이나면 바깥쪽 for문이 후연산으로 더해지는 과정입니다.

 

결과값입니다.

한문장이 완성되면 줄넘김처리를 해서 스크롤이 생긴것을 볼 수 있습니다.

 

2. table을 이용하여 구구단을 출력하는 방법

 

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>구구단</title>
    <script>
        document.write("<table>");
        document.write("<thead>");
        document.write("<tr>");
            for(let i = 2; i<=9; i++) {
                document.write("<th>"+i+"단"+"</th>");
            }
        document.write("</tr>");
        document.write("</thead>");
        document.write("<tbody>");
        
        for(let i = 1; i<=9; i++) {
            document.write("<tr>");
            for(let j = 2; j<=9; j++) {
                document.write("<td>" + j + "*" + i + "=" + (i*j) + " </td>");
            }
            document.write("</tr>");
        }
        document.write("</tbody>");
        document.write("</table>");
    </script>
</head>
<body>
    
</body>
</html>

설명에 앞서 2단부터 9단까지의 출력방법은 위와 다릅니다.

먼저 thead 부분은 구구단, body부분은 계산 부분으로 나누었습니다.

이중포문 부분에서 한 줄에 2*1=2 3*1=3 4*1=4 ... 9*1=9 처럼  2단부터 9단까지 모두 1을 곱한부분을 출력하고 줄넘김처리했습니다.

다음줄에서는 2*2=4 3*2=6 ... 9*2=18과 같이 마지막 줄 마지막 열을 9*9=81로 마무리하는 과정입니다.

중간에 tr과 td에 주의해서 보는게 이 코드의 특징입니다.

 

결과값입니다.

  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기