Front/JavaScript
[JavaScript] 반복문(while문, for문)
시월해
2021. 4. 23. 17:29
반복문 : 특정 구문을 여러 번 반복해서 실행하고자 할 때 사용하는 제어문.
반복문의 종류 : while문, for문
- while문은 주로 무한 반복하거나 반복 횟수가 정해지지 않은 경우에 사용.
- for문은 반복 횟수가 정해진 경우에 사용.
while문
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
// while문
let su = 1;
while(su <= 10) {
document.write("su >>> " + su + "<br>");
su++;
}
document.write("<hr>");
// [문제1] 1~100사이의 숫자 중에서 숫자가
// 4의 배수이면서 동시에 6의 배수인 숫자를 화면에 보여주세요.
let num = 1;
while(num <= 100) {
if(num%4 == 0 && num%6 == 0) {
document.write(num + " ");
}
num++;
}
document.write("<br>");
document.write("<hr>");
// [문제2] 1~100사이의 숫자 중에서 짝수인 경우는 글자색을 파란색으로
// 출력을 하고, 홀수인 경우에는 빨간색으로 화면에 출력해 보세요.
let number = 1;
while(number <= 100) {
if(number%2 == 1) {
document.write("<font color='red'>"+
number+"</font> ");
}else {
document.write("<font color='blue'>"+
number+"</font> ");
}
number++;
}
document.write("<br>");
</script>
</head>
<body>
</body>
</html>
for문
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
// for문
// 반복 횟수가 정해진 경우 많이 사용함.
for(let i=1; i<=10; i++) {
document.write("i >>> " + i + "<br>");
}
document.write("<hr>");
// [문제1] 1~100 사이의 숫자 중에서 5의 배수인 경우는 빨간색으로,
// 7의 배수인 경우는 초록색으로, 6의 배수인 경우에는
// 아쿠라(aqua) 색으로 화면에 출력해 보세요.
for(let i=1; i<=100; i++) {
if(i%5 == 0) {
document.write
("<font color='red'>"+i+"</font> ");
}else if(i%7 == 0) {
document.write
("<font color='green'>"+i+"</font> ");
}else if(i%6 == 0) {
document.write
("<font color='aqua'>"+i+"</font> ");
}else {
document.write
(i+"</font> ");
}
}
</script>
</head>
<body>
</body>
</html>
다중 for문
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
// 다중 for문
for(let i=2; i<10; i++) {
document.write("<p style='color: red;'>*** "+i+"단 ***</p>");
for(let j=1; j<10; j++) {
document.write(i+" * "+j+" = "+(i*j)+ "<br>");
}
}
</script>
</head>
<body>
</body>
</html>
for문과 테이블 태그를 이용하여 문제 내용대로 출력하기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
// [문제1]
// 1 2 3 4 5
// 6 7 8 9 10
// 11 12 14 14 15
// 16 17 18 19 20
// 21 22 23 24 25
let count = 1;
document.write("<table border='1' cellspacing='0' width='150'>");
for(let i=1; i<=5; i++) { // 행
document.write("<tr>");
for(let j=1; j<=5; j++) {
document.write("<td align='right'>"+count+"</td>");
count++;
}
document.write("</tr>");
}
document.write("</table>");
document.write("<hr>");
// [문제2]
// 1 6 11 16 21
// 2 7 12 17 22
// 3 8 13 18 23
// 4 9 14 19 24
// 5 10 15 20 25
document.write("<table border='1' cellspacing='0' width='150'>");
for(let i=1; i<=5; i++) {
document.write("<tr>");
for(let j=0; j<5; j++) {
document.write("<td align='right'>"+(j*5+i)+"</td>");
}
document.write("</tr>");
}
document.write("</table>");
</script>
</head>
<body>
</body>
</html>