책/멘토씨리즈 자바
[멘토씨리즈 자바] 05 - 제어문-2 - 응용문제
yn98
2024. 7. 18. 14:03
1. 다음 빈칸에 알맞은 단어를 작성해보세요.
- 반복문은 [ ] 한 동작을 여러 번 반복하여 실행하는 구문입니다.
더보기
동일
2. 반복문의 종류를 모두 나열해보세요.
더보기
- for
- for-each
- while
- do-while
- switch-case
3. 1부터 100 까지의 정수 중에서 짝수만을 더해 출력하는 코드를 for 문을 사용해 작성해보세요.
public static void main(String[] args) {
int res = 0; // 결과값 변수 0으로 초기화
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
res += i;
}
}
System.out.println(res);
}
4. 두 개의 주사위가 같은 값이 나올 때까지 while 문을 사용해 반복하고, 반복 횟수와 주사위 눈의 번호를 출력해보세요.
public static void main(String[] args) {
Random rand = new Random();
int cnt = 0; // 반복횟수 변수 = 0 초기화로 시작
while (true) {
cnt++;
int num1 = rand.nextInt(6) + 1; // 1~6까지 랜덤
int num2 = rand.nextInt(6) + 1;
if (num1 == num2) { // 주사위의 눈이 같으면
break;
}
}
System.out.println("반복 횟수 : "+cnt+" 주사위 눈의 번호 : " +num1+", "+num2);
}
5. 다중 반복문을 사용해 다음과 같은 모양의 *를 출력하는 코드를 작성해보세요.
* * * * * * * * * * |
public static void main(String[] args) {
int n = 4; // 행과 열의 수
for (int i = 0; i < n; i++) { // 행 반복
for (int j = 0; j < n - i - 1; j++) { // 왼쪽 공백 출력
System.out.print(" ");
}
for (int j = 0; j <= i; j++) { // 별 출력
System.out.print("*");
System.out.print(" ");
}
System.out.println(); // 줄 바꿈
}
}
6. 다중 반복문을 사용해 다음과 같은 모양의 *를 출력하는 코드를 작성해보세요.
* * * * * * * * * * * * * * * * |
public static void main(String[] args) {
int n = 4; // 총 행의 수
for (int i = 0; i < n; i++) { // 행 반복
for (int j = 0; j < (n - i - 1) * 2; j++) { // 왼쪽 공백 출력
System.out.print(" ");
}
for (int j = 0; j < i * 2 + 1; j++) { // 별 출력
System.out.print("*");
System.out.print(" ");
}
System.out.println();// 줄 바꿈
}
}