4-1 다음의 문장들을 조건식으로 표현하라.

1. int형 변수 x가 10보다 크고 20보다 작을 때 true인 조건식
2. char형 변수 ch가 공백이나 탭이 아닐 때 true인 조건식
3. char형 변수 ch가 ‘x' 또는 ’X'일 때 true인 조건식
4. char형 변수 ch가 숫자(‘0’~‘9’)일 때 true인 조건식
5. char형 변수 ch가 영문자(대문자 또는 소문자)일 때 true인 조건식
6. int형 변수 year가 400으로 나눠떨어지거나 또는 4로 나눠떨어지고 100으로 나눠떨어지지
않을 때 true인 조건식
7. boolean형 변수 powerOn가 false일 때 true인 조건식
8. 문자열 참조변수 str이 “yes”일 때 true인 조건식
		if (x > 10 && x < 20);
		if (ch == ' ' || ch=='	');
		if (ch=='x'||ch=='X');
		if (0<=ch&&ch<=9);
		if ('a'<=ch&&ch<='z'||'A'<=ch&&ch<='Z');
		if (year%400==0||(year%4==0&&year!=0));
		if (powerOn == false);
		if (str=="yes");

 

 

 

4-2 1부터 20까지의 정수 중에서 2 또는 3의 배수가 아닌 수의 총합을 구하시오.

public class JavaExercise4_2 {
	public static void main(String[] args) {
		int i = 0;
		int sum = 0;

		for (i = 1; i <= 20; i++) {
			if (i % 2 != 0 && i % 3 != 0) {
				sum += i;
			}
		};
		System.out.println(sum);
	}
}
73

 

 

 

4-3 1+(1+2)+(1+2+3)+(1+2+3+4)+...+(1+2+3+...+10)의 결과를 계산하시오.

public class JavaExercise4_3 {
	public static void main(String[] args) {
		int i=1;
		int a=0;
		int s=0;
		
		for(i=1;i<=10;i++) {
			a=a+i;
			s=s+a;			
		}
		System.out.println(s);
	}
}
220

 

 

 

4-4 1+(-2)+3+(-4)+... 과 같은 식으로 계속 더해나갔을 때, 몇까지 더해야 총합이 100 이상이 되는지 구하시오.

public class JavaExercise4_4 {
	public static void main(String[] args) {
		int sum = 0; // 총합을 저장할 변수
		int s = 1; // 값의 부호를 바꿔주는데 사용할 변수
		int num = 0;
		// 조건식의 값이 true이므로 무한반복문이 된다.
		for (int i = 1; sum < 100; i++) {
			s = -s;
			num = i * s;
			sum += num;
		}
		System.out.printf("num= %d%n",num-1);
		System.out.printf("sum= %d", sum);
	} // main
}
num= 199
sum= 100

 

 

4-5 다음의 for문을 while문으로 변경하시오.

	public static void main(String[] args) {
		for (int i = 0; i <= 10; i++) {
			for (int j = 0; j <= i; j++)
				System.out.print("*");
			System.out.println();
		}
	} // end of main
} // end of class
public class JavaExercise4_5 {
	public static void main(String[] args) {
		int i = 0;

		while (i <= 10) {
			int j = 0;
			while (j <= i) {
					System.out.printf("*");
					j++;
					}

			System.out.println();
			i++;
				}
		} // end of main
	}  // end of class

 

 

 

4-6 두 개의 주사위를 던졌을 때, 눈의 합이 6이 되는 모든 경우의 수를 출력하는 프로그램을 작성하시오.

public class JavaExercise4_6 {
	public static void main(String[] args) {
		int i=0;
		int j=0;
		for(i=1;i<6;i++) {
			j=6-i;
			System.out.printf("[%d, %d]",i ,j);
			System.out.println();
		}
	}
}
[1, 5]
[2, 4]
[3, 3]
[4, 2]
[5, 1]

 

 

4-7 Math.random()을 이용해서 1부터 6사이의 임의의 정수를 변수 value에 저장하는 코드를 완성하라. (1)에 알맞은 코드를 넣으시오.

public class JavaExercise4_7 {
	public static void main(String[] args) {
		int value = ( /* (1) */ );
		System.out.println("value:"+value);
		}
}
(int)Math.random()*6+1
value:1

 

 

 

4-8 방정식 2x+4y=10의 모든 해를 구하시오. 단, x와 y는 정수이고 각각의 범위는 0 <=x <=10, 0 <=y <=10이다.

public class JavaExercise4_8 {
	public static void main(String[] args) {
		int x = 0;
		int y = 2;
		for (x = 1; x <= 10; x++) {
			for (y = 0; y <= 10; y++) {
				if (2 * x + 4 * y == 10) {
					System.out.println("x=" + x + ", y=" + y);
				}
			}
		}
	}
}
x=1, y=2
x=3, y=1
x=5, y=0

 

4-9 숫자로 이루어진 문자열 str이 있을 때, 각 자리의 합을 더한 결과를 출력하는 코드를 완성하라. 만일 문자열이 "12345"라면, ‘1+2+3+4+5’의 결과인 15를 출력이 출력되어야 한다. (1)에 알맞은 코드를 넣으시오.
[Hint] String클래스의 charAt(int i)을 사용

public class JavaExercise4_9 {
	public static void main(String[] args) {
		String str = "12345";
		int sum = 0;
		for (int i = 0; i < str.length(); i++) {
		/*
		(1) 알맞은 코드를 넣어 완성하시오.
		*/
		}
		System.out.println("sum=" + sum);
	}
}
public class JavaExercise4_9 {
	public static void main(String[] args) {
		String str = "12345";
		int sum = 0;
		for (int i = 0; i < str.length(); i++) {
			sum += str.charAt(i)-'0';
		}
		System.out.println("sum=" + sum);
	}
}
sum=15

 

 

 

4-10 int타입의 변수 num 이 있을 때, 각 자리의 합을 더한 결과를 출력하는 코드를 완성하라. 만일 변수 num의 값이 12345라면, ‘1+2+3+4+5’의 결과인 15를 출력하라. (1)에 알맞은 코드를 넣으시오.
[주의] 문자열로 변환하지 말고 숫자로만 처리해야 한다.

public class JavaExercise4_10 {
	public static void main(String[] args) {
		int num = 12345;
		int sum = 0;
		/*
			(1) 알맞은 코드를 넣어 완성하시오.
		*/
		System.out.println("sum=" + sum);
	}
}
public class JavaExercise4_10 {
	public static void main(String[] args) {
		int num = 12345;
		int sum = 0;
		for (int i = 0; i<=5; i++) {
			sum = num % 10 + sum;
			num = (num-num%10)/10;
		}
		System.out.println("sum=" + sum);
	}
}

 

 

 

4-11 피보나치(Fibonnaci) 수열(數列)은 앞을 두 수를 더해서 다음 수를 만들어 나가는 수열이다. 예를 들어 앞의 두 수가 1과 1이라면 그다음 수는 2가 되고 그 다음 수는 1과 2를 더해서 3이 되어서 1,1,2,3,5,8,13,21,... 과 같은 식으로 진행된다. 1과 1부터 시작하는 피보나치수열의 10번째 수는 무엇인지 계산하는 프로그램을 완성하시오.

public class JavaExercise4_11 {
	public static void main(String[] args) {
		// Fibonnaci 수열의 시작의 첫 두 숫자를 1, 1로 한다.
		int num1 = 1;
		int num2 = 1;
		int num3 = 0; // 세번째 값
		System.out.print(num1 + "," + num2);

		for (int i = 0; i < 8; i++) {
		/*
			(1) 알맞은 코드를 넣어 완성하시오.
		*/
		}
	}// end of main
}// end of class
public class JavaExercise4_11 {
	public static void main(String[] args) {
		// Fibonnaci 수열의 시작의 첫 두 숫자를 1, 1로 한다.
		int num1 = 1;
		int num2 = 1;
		int num3 = 0; // 세번째 값
		System.out.print(num1 + "," + num2);

		for (int i = 0; i < 8; i++) {

			num3 = num1 +num2;
			num1 = num2;
			num2 = num3;
			System.out.print(","+num3);
		}
	}// end of main
}// end of class

 

4-12 구구단의 일부분을 다음과 같이 출력하시오.

public class JavaExercise4_12 {
	public static void main(String[] args) {
		for (int i = 1; i <= 9; i++) {
			for (int j = 1; j <= 3; j++) {
				int x = j + 1 + (i - 1) / 3 * 3;
				int y = i % 3 == 0 ? 3 : i % 3;
				if (x > 9) // 9단까지만 출력한다. 이 코드가 없으면 10단까지 출력된다.
					break;
				System.out.print(x + "*" + y + "=" + x * y + "\t"); // println이 아님에 주의
			}
			System.out.println();
			if (i % 3 == 0)
				System.out.println(); //
		}
	} // end of main
} // end of class
public class JavaExercise4_12_1 {
	public static void main(String[] args) {
		int n = 2;
		for (int j = 1; j <= 3; j++) {
			for (int i = 1; i <= 3; i++) {
				System.out.printf("%dx%d=%d\t", n, i, n * i);
				System.out.printf("%dx%d=%d\t", n + 1, i, (n + 1) * i);
				if(n!=8) 
				System.out.printf("%dx%d=%d", n + 2, i, (n + 2) * i);
				System.out.println();
			}
			n +=3;
			System.out.println();
		}
	}
}
2x1=2	3x1=3	4x1=4
2x2=4	3x2=6	4x2=8
2x3=6	3x3=9	4x3=12

5x1=5	6x1=6	7x1=7
5x2=10	6x2=12	7x2=14
5x3=15	6x3=18	7x3=21

8x1=8	9x1=9	
8x2=16	9x2=18	
8x3=24	9x3=27

 

 

4-13 다음은 주어진 문자열(value)이 숫자인지를 판별하는 프로그램이다. (1)에 알맞은 코드를 넣어서 프로그램을 완성하시오.

public class JavaExercise4_13 {
	public static void main(String[] args) {
		String value = "12o34";
		char ch = ' ';
		boolean isNumber = true;
		// 반복문과 charAt(int i)를 이용해서 문자열의 문자를
		// 하나씩 읽어서 검사한다.
		for (int i = 0; i < value.length(); i++) {
			/*
				(1) 알맞은 코드를 넣어 완성하시오.
			*/
			}
		}
		if (isNumber) {
			System.out.println(value + "는 숫자입니다.");
		} else {
			System.out.println(value + "는 숫자가 아닙니다.");
		}
	} // end of main
} // end of class
public class JavaExercise4_13 {
	public static void main(String[] args) {
		String value = "12o34";
		char ch = ' ';
		boolean isNumber = true;
		// 반복문과 charAt(int i)를 이용해서 문자열의 문자를
		// 하나씩 읽어서 검사한다.
		for (int i = 0; i < value.length(); i++) {
			ch = value.charAt(i);
			if ('0' >= ch || ch >= '9'|| isNumber==false) {
				isNumber = false;
				break;
			}
		}
		if (isNumber) {
			System.out.println(value + "는 숫자입니다.");
		} else {
			System.out.println(value + "는 숫자가 아닙니다.");
		}
	} // end of main
} // end of class
12o34는 숫자가 아닙니다.

 

 

4-14 다음은 숫자 맞추기 게임을 작성한 것이다. 1과 100 사이의 값을 반복적으로 입력해서 컴퓨터가 생각한 값을 맞추면 게임이 끝난다. 사용자가 값을 입력하면, 컴퓨터는 자신이 생각한 값과 비교해서 결과를 알려준다. 사용자가 컴퓨터가 생각한 숫자를 맞추면 게임이 끝나고 몇 번 만에 숫자를 맞췄는지 알려준다. (1)~(2)에 알맞은 코드를 넣어 프로그램을 완성하시오.

public class JavaExercise4_14 {
	public static void main(String[] args) {
		// 1~100사이의 임의의 값을 얻어서 answer에 저장한다.
		int answer =  /* (1) */;
		int input = 0; // 사용자입력을 저장할 공간
		int count = 0; // 시도횟수를 세기위한 변수
		// 화면으로 부터 사용자입력을 받기 위해서 Scanner클래스 사용
		java.util.Scanner s = new java.util.Scanner(System.in);
		/*
			(2) 알맞은 코드를 넣어 완성하시오.
		*/	
		}
		while (true); // 무한반복문
	} // end of main
} // end of class HighLow
public class JavaExercise4_14 {
	public static void main(String[] args) {
		// 1~100사이의 임의의 값을 얻어서 answer에 저장한다.
		int answer = (int) (Math.random() * 100) + 1;
		int input = 0; // 사용자입력을 저장할 공간
		int count = 0; // 시도횟수를 세기위한 변수
		// 화면으로 부터 사용자입력을 받기 위해서 Scanner클래스 사용
		java.util.Scanner s = new java.util.Scanner(System.in);
		do {
			count++;
			System.out.print("1과 100사이의 값을 입력하세요 :");
			input = s.nextInt(); // 입력받은 값을 변수 input에 저장한다.
			if (answer > input) {
				System.out.println("더 큰 수를 입력하세요.");
			} else if (answer < input) {
				System.out.println("더 작은 수를 입력하세요.");
			} else {
				System.out.println("맞췄습니다.");
				System.out.println("시도횟수는 " + count + "번입니다.");
				break;
				// do-while문을 벗어난다
				
			}
		}
		while (true); // 무한반복문
	} // end of main
} // end of class HighLow
1과 100사이의 값을 입력하세요 :50
더 작은 수를 입력하세요.
1과 100사이의 값을 입력하세요 :25
더 큰 수를 입력하세요.
1과 100사이의 값을 입력하세요 :37
더 작은 수를 입력하세요.
1과 100사이의 값을 입력하세요 :31
맞췄습니다.
시도횟수는 4번입니다.

 

 

4-15 다음은 회 문수를 구하는 프로그램이다. 회 문수(palindrome)란, 숫자를 거꾸로 읽어도 앞으로 읽는 것과 같은 수를 말한다. 예를 들면 ‘12321’이나 ‘13531’ 같은 수를 말한다. (1)에 알맞은 코드를 넣어서 프로그램을 완성하시오.
[Hint] 나머지 연산자를 이용하시오.

public class JavaExercise4_15 {
	public static void main(String[] args) {
		int number = 12321;
		int tmp = number;
		int result = 0; // 변수 number를 거꾸로 변환해서 담을 변수
		
		while (tmp != 0) {
		/*
			(1) 알맞은 코드를 넣어 완성하시오.
		*/
		}
		if (number == result)
			System.out.println(number + "는 회문수 입니다.");
		else
			System.out.println(number + "는 회문수가 아닙니다.");
	} // main
}
public class JavaExercise4_15 {
	public static void main(String[] args) {
		int number = 12321;
		int tmp = number;
		int result = 0; // 변수 number를 거꾸로 변환해서 담을 변수
		
		while (tmp != 0) {
			result = result * 10 + tmp % 10; // 기존 결과에 10을 곱해서 더한다.
			tmp /= 10;
		}
		if (number == result)
			System.out.println(number + "는 회문수 입니다.");
		else
			System.out.println(number + "는 회문수가 아닙니다.");
	} // main
}
12321는 회문수 입니다.

break문은 근접한 단 하나의 반복문만 벗어날 수 있기 때문에, 여러 개의 반복문이 중첩된 경우에는 break문으로 중첩된 반복문을 완전히 벗어날 수 없다. 이때 이름 붙은 반복문으로 하나 이상의 반복문을 벗어나거나 반복을 건너뛸 수 있다.

 

public class FlowEx33 {
	public static void main(String[] args) {
		// for문에 Loop1이라는 이름을 붙였다.
		Loop1:
			for (int i = 2; i <= 9; i++) {
			for (int j = 1; j <= 9; j++) {
				if (j == 5)
//				break Loop1;
//				break;
//				continue Loop1;
				continue;
				System.out.println(i + "*" + j + "=" + i * j);
			} // end of for i
			System.out.println();
		} // end of Loop1
	}
}
2*1=2
2*2=4
2*3=6
2*4=8
2*6=12
2*7=14
2*8=16
2*9=18

3*1=3
3*2=6
3*3=9
3*4=12
3*6=18
3*7=21
3*8=24
3*9=27

4*1=4
4*2=8
4*3=12
4*4=16
4*6=24
4*7=28
4*8=32
4*9=36

5*1=5
5*2=10
5*3=15
5*4=20
5*6=30
5*7=35
5*8=40
5*9=45

6*1=6
6*2=12
6*3=18
6*4=24
6*6=36
6*7=42
6*8=48
6*9=54

7*1=7
7*2=14
7*3=21
7*4=28
7*6=42
7*7=49
7*8=56
7*9=63

8*1=8
8*2=16
8*3=24
8*4=32
8*6=48
8*7=56
8*8=64
8*9=72

9*1=9
9*2=18
9*3=27
9*4=36
9*6=54
9*7=63
9*8=72
9*9=81

 

i * 5의 식이 생략되었다.

 

public class FlowEx34 {
	public static void main(String[] args) {
		int menu = 0, num = 0;
		
		Scanner scanner = new Scanner(System.in);
		
		outer:
			while(true) {
				System.out.println("(1) square");
				System.out.println("(2) square root");
				System.out.println("(3) log");
				System.out.println("원하는 메뉴(1~3)를 선택하세요.(종료0)>");
				
				String tmp = scanner.nextLine();	// 화면에서 입력받은 내용을 tmp에 저장
				menu = Integer.parseInt(tmp);		// 입력받은 문자열(tmp)를 숫자로 변환
				
				if(menu==0) {
					System.out.println("프로그램을 종료합니다.");
					break;
				}else if (!(1<= menu && menu <=3)) {
					System.out.println("메뉴를 잘못 선택하셨습니다.(종료는0)");
					continue;
				}
				
				for(;;) {
					System.out.print("계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>");
					tmp = scanner.nextLine();		// 화면에서 입력받은 내용을 tmp에 저장
					num = Integer.parseInt(tmp);	// 입력받은 문자열(tmp)를 숫자로 변환
					
					if(num==0)
						break;
					
					if(num==99)
						break outer;
					
					switch(menu) {
					case 1:
						System.out.println("result="+ num*num);
						break;
					case 2:
						System.out.println("result="+ Math.sqrt(num));
						break;
					case 3:
						System.out.println("result="+ Math.log(num));
						break;
					}
				} // for(;;)
			} // while의 끝
	}// main의 끝
}
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)를 선택하세요.(종료0)>
1
계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>2
result=4
계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>0
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)를 선택하세요.(종료0)>
2
계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>4
result=2.0
계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>99

 

예제 4-32에서 코드를 추가한 것이다.

 

반복문만 떼어놓고 보면 무한 반복문인 while문 안에 또 다른 무한 반복문 for문의 중첩된 구조이다.

outer :
while(true) {
	...
    for( ; ; )
    	...
        if(num==0) // 계산 종료. for문을 벗어난다.
        	break;
            if*num==99) // 전체 종료. for문과 while문 모두 벗어난다.
            	break outer;
                ...
            } // for( ; ; )
        } // while(true)

break outer에 의해 for문과 while문 모두를 벗어나 프로그램이 종료된다.

'JAVA 04강 조건문과 반복문 > 반복문break, continue, 명명된반복문' 카테고리의 다른 글

continue문  (0) 2021.07.15
break문  (0) 2021.07.15

continue문은 반복문 내에서만 사용될 수 있으며, 반복이 진행되는 도중에 continue문을 만나면 반복문의 끝으로 이동하여 다음 반복문으로 넘어간다.

for문의 경우 증감식으로 이용하며 while문의 경우 조건식으로 이용한다.

 

import java.util.*;

public class FlowEx32 {
	public static void main(String[] args) {
		int menu = 0;
//		int num = 0;

		Scanner scanner = new Scanner(System.in);

		while (true) {
			System.out.println("(1) square");
			System.out.println("(2) square root");
			System.out.println("(3) log");
			System.out.println("원하는 메뉴(1~3)를 선택하세요. (종료:0)>");

			String tmp = scanner.nextLine();// 화면에서 입력받은 내용을 tmp에 저장
			menu = Integer.parseInt(tmp);

			if (menu == 0) {
				System.out.println("프로그램을 종료합니다.");
				break;
			} else if (!(1 <= menu && menu <= 3)) {
				System.out.println("메뉴를 잘못 선택하셨습니다.(종료는 0)");
				continue;
			}

			System.out.println("선택하신 메뉴는 " + menu + "번입니다.");
		}
		scanner.close();
	}
}
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)를 선택하세요. (종료:0)>
4
메뉴를 잘못 선택하셨습니다.(종료는 0)
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)를 선택하세요. (종료:0)>
1
선택하신 메뉴는 1번입니다.
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)를 선택하세요. (종료:0)>
0
프로그램을 종료합니다.

메뉴를 보여주고 선택하게하는 예제이다.

잘못 선택한경우 다시 while문의 처음으로 돌아간다.

'JAVA 04강 조건문과 반복문 > 반복문break, continue, 명명된반복문' 카테고리의 다른 글

이름 붙은 반복문  (0) 2021.07.15
break문  (0) 2021.07.15

앞서 switch문에서 break문에 대해 배웠던 것 처럼 반복문에서도 break문을 사용할 수 있다.

주로 if문과 함께 사용되어 조건을 만족하면 반복문을 벗어나도록한다.

public class FlowEx30 {
	public static void main(String[] args) {
		int sum = 0;
		int i = 0;
		
		while(true) {
			if(sum > 100)
				break;
			++i;
			sum +=i;
		}// end of while
		
		System.out.println("i=" + i);
		System.out.println("sum=" + sum);
	}
}
i=14
sum=105

숫자를 1부터 더해서 몇까지 더하면 합이 100을넘는지 알아내는 예제이다.

14에서 합105가되어 반복문을 벗어난다.

for문에 비해 while문은 구조가 간단하다.

while (조건식) {
	//조건식의 연산결과가 참(true)인 동안, 반복될 문장들을 적는다.
}
1. 조건식이 참(true)이면 블럭{}안으로 들어가고, 거짓(false)이면 while문을 벗어난다.
2. 블럭{}의 문장을 수행하고 다시 조건식으로 돌아간다.

 

 

for문과 while문의 비교

for(int i=1;i<=10;i++) {
	System.out.println(i);
}

 

while(i<=10) {
	System.out.println(i);
    i++;
}

for문과 while문은 항상 서로 변환이 가능하다.

초기화나 증감 식이 없다면 while문이 더 적합할 것이다.

 

while문의 조건식은 생략불가

for문은 조건식을 생략할 수 있으나 for( ; ; )이 가능하나

while문의 조건식은 생략할 수 없다. while( ) 은 불가능

따라서 while문은 적어도 while(true)를 적어줘야한다.

 

public class FlowEx23 {
	public static void main(String[] args) {
		int i = 5;

		while (i-- != 0) {
			System.out.println(i + " - I can do it.");
		}
	}	//main의 끝
}
4 - I can do it.
3 - I can do it.
2 - I can do it.
1 - I can do it.
0 - I can do it.

'JAVA 04강 조건문과 반복문 > 반복문 for, while' 카테고리의 다른 글

반복문 do-while  (0) 2021.07.15
반복문 for  (0) 2021.07.15

for문이나 while문에 속한 문장은 조건에 따라 한 번도 수행되지 않을 수 있지만 do-wheile문에 속한 문장은 무조건 최소한 한 번은 수행될 것이 보장된다.

주로 게임에서 이를 이용한다.(e.g. UI 튜토리얼)

기본적으로 while문과 구조가 같으나 조건식과 블록{}의 순서를 바꿔놓은 것이다.

do {
	//조건식의 연산결과가 참일 때 수행될 문장들을 적는다.
    } while {조건식);

그리 많이 쓰는 반복문은 아니다.

 

public class FlowEx28 {
	public static void main(String[] args) {
		int input = 0, answer = 0;

		answer = (int) (Math.random() * 100) + 1; // 1~100사이의 임의의 수를 저장
		Scanner scanner = new Scanner(System.in);

		do {
			System.out.print("1과 100사이의 정수를 입력하세요.>");
			input = scanner.nextInt();

			if (input > answer) {
				System.out.println("더 작은 수로 다시 시도해보세요.");
			} else if (input < answer) {
				System.out.println("더 큰 수로 다시 시도해보세요.");
			}
		} while (input != answer);

		System.out.println("정답입니다.");
		scanner.close();
	}
}
1과 100사이의 정수를 입력하세요.>50
더 큰 수로 다시 시도해보세요.
1과 100사이의 정수를 입력하세요.>75
정답입니다.

 

'JAVA 04강 조건문과 반복문 > 반복문 for, while' 카테고리의 다른 글

반복문while  (0) 2021.07.15
반복문 for  (0) 2021.07.15

반복문은 어떤 작업이 반복적으로 수행되도록 할 때 사용된다.

for문과 while문은 구조와 기능이 유사하여 어느 경우에나 서로 변환이 가능하다.

 

for문

for문은 반복 횟수를 알고 있을 때 적합하다.

구조가 객관적이라 이해하기 쉽다.

for(int i=1i<=5;i++) {
	System.out.println("I can do it.");
}

변수에 i를 저장한 다음, 매 반복마다 i값을 i 증가시키고, 반복할 때마다 "I can do it"을 출력한다.

 

for문의 구조와 수행 순서

for문은 초기화, 조건식, 증감식, 블록{}으로 이루어져 있으며, 조건식이 참인 동안 블록{ } 내의 문장들을 반복한다.

for (초기화;조건식;증감식) {
	// 조건식이 참일 때 수행될 문장들을 적는다.
)
1. 초기화 수행
2. 조건식 참거짓 판별
3. 수행될 문장
4. 증감식
5. 다시 2로

 

초기화

반복문에 사용될 변수를 초기화하는 부분이며 처음에 한 번만 수행된다.

 

조건식

조건식의 값이 (boolean) 참(true)이면 반복을 계속하고, false이면 반복을 중단한다.

조건식을 잘못 만들면 한 번도 수행되지 않거나, 영원히 반복된다.

 

증감식

반복문을 제어하는 변수의 값을 증가 또는 감소시키는 식이다.

 

public class FlowEx14 {
	public static void main(String[] args) {
		for (int i = 1; i <= 10; i++) { // 반복횟수 가급적 for문에서는 시작의 변수는 하나만
			System.out.printf("%d \t%n", i);
		}
	}
}
1 	
2 	
3 	
4 	
5 	
6 	
7 	
8 	
9 	
10

 

중첩 for문

if안에 또 다른 if문을 넣을 수 있는 것처럼, for문 안에 또 다른 for문을 포함시키는 것도 가능하다.

public class FlowEx16 {
	public static void main(String[] args) {
		for(int i=1; i<=5;i++) {
			for(int j=1;j<=10;j++) {
				System.out.print("*");// 2 10
			}
			System.out.println();
		}
	}

}
**********
**********
**********
**********
**********
(j=1,i=1) 2,1 3,1 4,1 5,1
1,2 2,2 3,2 4,2 5,2
1,3 2,3 3,3 4,3 5,3
1,4 2,4 3,4 4,4 5,4
1,5 2,5 3,5 4,5 5,5

for( i증가식 ) {

for( j증가식) {

"*"}

}

연산순서

1. i 증가
2. j 증가
3. * 출력
4. j 증가 * 4
5. 다시 1번부터 4회 추가로 반복

 

향상된 for문(enhanced for statement)

JDK1.5부터 배열과 컬렉션에 저장된 요소에 접근할 때 기존보다 편리한 방법으로 처리할 수 있도록 for문의 새로운 문법이 추가되었다.

향상된 for문을 사용하려면 객체가 필요하다.

for ( 타입 변수명 : 배열 또는 컬렉션) {
	// 반복할 문장
}

 

int[] arr = {10,20,30,40,50);

for(int i=0; i < arr.length; i++) {
	System.out.println(arr[i]);
}

이 문장을 배열을 선언했을 때

int[] arr = {10,20,30,40,50);

for(int tmp : arr) {
	System.out.println(tmp);
}

이런 식으로 표현이 가능해진다.

그러나 향상된 for문은 일반적인 for문과 달리 배열이나 컬렉션에 저장된 요소들을 읽어오는 용도로만 사용할 수 있다.

 

'JAVA 04강 조건문과 반복문 > 반복문 for, while' 카테고리의 다른 글

반복문while  (0) 2021.07.15
반복문 do-while  (0) 2021.07.15

+ Recent posts