자바(Java)학습/1_Java 기초
20.중첩 반복문
thespeace
2021. 8. 23. 19:19
중첩반복문이란?
반복문 내부에 또 다른 반복문을 넣는다
여러 겹으로 반복문을 겹쳐서 구현 가능합니다 (단 수행시간에 문제가 발생할 수 있습니다)
따라서 외부 반복문과 내부 반복문간의 변수 값 변화에 유의하며 구현해야 합니다
구구단을 for와 while로 구현해 보자
package 20;
public class NestedLoopTest {
public static void main(String[] args) {
int dan = 2;
int count = 1;
for( ; count <= 9; count++) {
System.out.println(dan+"X"+count+"="+dan*count);
}
}
}
/*Console :
2X1=2
2X2=4
2X3=6
2X4=8
2X5=10
2X6=12
2X7=14
2X8=16
2X9=18 */
dan = 2, 2는 변하지 않는다
count = 1~9까지 변화 한다
-프로그래밍 원리중의 하나인다. 변화 한다, 변하지 않는다.
dan*count = 변화 한다.
dan도 변화시켜보자.
package 20;
public class NestedLoopTest {
public static void main(String[] args) {
int dan = 2;
int count;
for( ; dan <= 9; dan++) {
for(count = 1; count <= 9; count++) {
System.out.println(dan+"X"+count+"="+dan*count);
}
System.out.println(); //줄바꿈
}
}
}
//Console : 2단부터 9단까지 잘 출력된다.
컴파일러에게 모든걸 맡기고 결과만 받게되면 문제가 생길 수 있고, 해결하기도 쉽지않다
따라서 인간의 머리로도 그림을 그려가며 프로그래밍을 해야한다.
package 20;
public class NestedLoopTest {
public static void main(String[] args) {
int dan = 2;
int count = 1;
while(dan <= 9) {
count=1;
while(count <= 9) {
System.out.println(dan+"X"+count+"="+dan*count)
count++;
}
dan++;
System.out.println();
}
}
}
//Console : 2단~9단 정상 출력