for문을 이용한 반복 코드의 이해

Seong Hyeon Kim·2022년 3월 18일
0

개인공부

목록 보기
15/23

우선 for문의 코드방식에 대해 간단한 코드로 설명을 해보자

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        var sum = 0;

        for(1️⃣var i = 1; 2️⃣i < 101; 4️⃣i++){
            3️⃣sum += i;
        }
        document.write("1부터 100까지 더하면" + sum);
    </script>
</body>
</html>

1️⃣ 카운터 변수선언 : for문에서만 사용할 카운터 변수 선언

2️⃣ for 문의 조건식 : for문 안에 소스를 실행할지 판단하는 조건식.true 라면 중괄호 안의 자바스크립트 소스를 실행 하고, false 라면 for문을 벗어나 다음 소스를 진행

3️⃣ 반복 실행할 자바스크립트 소스 : for 문에서 실행할 중괄호 자바s소스

4️⃣ 카운터 변수 조절 : 증감 연산자를 사용 카운터 변수 조절한다. 위 소스에서는 중괄호를 실행한 이후 카운터 변수 i를 1만큼 증가 (i++)

for문을 실행시 반복횟수의 기준이 되는 카운터 변수는 그 이름을 아무거나 써도 되지만, 보통 i로 많이 
한다.

또한 카운터 변수는 반목문 시작전 반드시 초기화 해야하며,
보토 for문의 반복 실행 횟수만 알아낼때는 변수를 i=0 으로 많이 하지만 
여기서는 덧셈에 사용하기 위해 1로 초기화햇음

for 중첩문 사용

<!DOCTYPE html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>중첩된 for</title>
	<link rel="stylesheet" href="css/for.css">
</head>
<body>
	<script>
		for(var i=0; i<30; i++){  //i=0 부터 i=29까지 총 30회 반복한다는 말
			document.write("*")
		}

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

이 코드대로 적으면 30번 반복하며 한번 반복할때마다 * 하나를 생성해서 한줄을 만들게 된다

만약 이런 줄을 5개 만들고 싶으면

<!DOCTYPE html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>중첩된 for</title>
	<link rel="stylesheet" href="css/for.css">
</head>
<body>
	<script>
		for(var i=0; i<30; i++){
			document.write("*")
		}
		document.write("<br>");
		for(var i=0; i<30; i++){
			document.write("*")
		}
		document.write("<br>");
		for(var i=0; i<30; i++){
			document.write("*")
		}
		document.write("<br>");
		for(var i=0; i<30; i++){
			document.write("*")
		}
		document.write("<br>");
		for(var i=0; i<30; i++){
			document.write("*")
		}
	</script>
</body>
</html>

줄바꿈 의미인
태그를 추가해서 복붙 5번 하면된다. 근데 그러면 코드가 너무 복잡하고 지저분해진다.

하지만 위에 코드 및에


document.write("<br><br>");

for(var k = 0; k<5; k++){  1️⃣    4️⃣
			for(var i=0; i<30; i++){  2️⃣
			document.write("*")		  2️⃣
			} 						  2️⃣
			document.write("<br>");       3️⃣
		}

라는 코드를 추가해서 만들면 이렇게 원래 있던 5줄에 코드몇줄로 5줄이 더 생성될수잇다

작동원리:

1. 맨 윗줄 for문을 실행한다 (k=o)

2. 안쪽 for문을 30번반복후 빠져나옵니다 ()

3. <br> 태그를 추가해서 줄바꿈

4. 맨 윗줄 for문의 조건식이 false가 될때까지 반복한다.

연습문제 구구단 코딩

  • 구구단 코딩
<!DOCTYPE html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>구구단 - for</title>
	<link rel="stylesheet" href="css/gugudan.css">
</head>
<body>
	<h1>구구단</h1>
	<script>
		for(var i = 2; i <= 9; i++){
			document.write ("<div>");
			document.write ("<h3>" + i + "단</h3>");
			for (var j = 1; j <= 9; j++){
				document.write(i + "x" + j + "=" + i*j + "<br>")
			}
			document.write("</div>");
		}


	</script>

</body>
</html>

구구단의 각 단수는 첫번째 i 변수로 설정하였고
단수에 곱해지는 수는 j 변수로 만들었으며,
for문 i 안에 j 를 하나 더 만들어줌으로써 구구단 완성!

profile
삽질도 100번 하면 요령이 생긴다. 부족한 건 경험으로 채우는 백엔드 개발자

0개의 댓글