10일 차 - 반복문, 무한루프, for중첩문(23.01.06)

yvonne·2023년 1월 6일
0

📂Java

목록 보기
10/51

1. 아래와 같이 출력이 되도록 구현하시오. (for 중첩문)

  • --------------------
    [0, 0] [0, 1] [0, 2]
    --------------------
    [1, 0] [1, 1] [1, 2]
    --------------------
    [2, 0] [2, 1] [2, 2]
public class ForPractice2 {

	public static void main(String[] args) {
		for(int i = 0; i <3;i++) {
			System.out.println("--------------------");
			for(int j = 0; j <3 ; j++) {
				System.out.print("[" + i + ", " + j + "] ");
			}
			System.out.println();
		}

	}

}
  • 출력결과


2. 아래를 프로그래밍 하시오.

1) 구구단을 나오게 하시오.

public class ForPractice2 {

	public static void main(String[] args) {
		for (int i = 2; i <= 9; i++) {

			for (int j = 1; j <= 9; j++) {
				System.out.println(i + " x " + j + " = " + (i * j));
			}
			System.out.println();
		}

	}

}
  • 출력결과

2) 3의 배수인 단만 나오게 하시오.

public class ForPractice2 {

	public static void main(String[] args) {
		for (int i = 2; i <= 9; i++) {
			if (i % 3 != 0) {
				continue; 
                // continue문으로 조건 걸어주기
			}
			for (int j = 1; j <= 9; j++) {
				System.out.println(i + " x " + j + " = " + (i * j));
			}
			System.out.println();
		}

	}

}
  • 출력결과

3) 구구단의 총합을 구하시오.

public class ForPractice2 {

	public static void main(String[] args) {
		int sum = 0;
		for (int i = 1; i <= 9; i++) {
			for (int j = 1; j <= 9; j++) {
				sum += (i * j);

			}
		}
		System.out.println("1단부터 9단까지 곱셈의 합: " + sum);

	}

}
  • 출력결과

4) 짝수인단만 나오게 하시오

public class ForPractice2 {

	public static void main(String[] args) {

		for (int i = 2; i <= 9; i++) {
			if (i % 2 != 0) {
				continue;
			}
			for (int j = 1; j <= 9; j++) {
				System.out.println(i + " x " + j + " = " + (i * j));

			}
			System.out.println();
		}

	}

}
  • 출력결과

5) 구구단을 9단부터 나오게 하시오.

public class ForPractice2 {

	public static void main(String[] args) {

		for (int i = 9; i > 1; i--) {

			for (int j = 9; j > 0; j--) {
				System.out.println(i + " x " + j + " = " + (i * j));

			}
			System.out.println();
		}

	}

}
  • 출력결과


3. 반복문 3가지의 무한루프 만드는 방법은?

  • for문
for( ; ; ) {  	// 또는 for( ;true; )도 가능함
	 ....
	 } 

  • while문
while(true) {
	....
    }

  • do~while문
do {
	....
} while(true)
  • 무한루프에서 빠져나가기 위해서는 break; 해야함


4. while 문으로 구구단을 찍어 보시오.



public class ForPractice2 {

	public static void main(String[] args) {
		int i = 2;

		while (i < 10) {
			int j = 1; 
            //j값의 초기화를 위에다 하면 j값이 9인채로 연산이 진행되기 때문에!! 여기에다 넣어야함
			while (j < 10) {
				System.out.println(i + " x " + j + " = " + (i * j));
				j++;
				continue;
			}
			System.out.println();
			i++;
		}
	}
}

        
        
  • 출력결과


5. 아래의 Star를 찍으시오.

*****
*****
*****
*****
*****

public class ForPractice {

	public static void main(String[] args) {

		for (int i = 0; i < 5; i++) {
			for (int j = 0; j < 5; j++) {
				System.out.print("*");
			}
		System.out.println();
		}
	}

}
  • 출력결과
profile
개발 연습장

0개의 댓글