본문 바로가기

TIL/Java

[Java] 반복문(for, while), 분기문(break, continue)

for 조건문

for(초기화; 조건식; 증감식) {
           조건을 만족하는 경우 수행할 구문(반복할 구문);
};
for(int i = 1; i <= 10; i += 2) {    =>  1부터, 10까지, 2씩증가 
System.out.println(i); }

 

초기화

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

조건식

조건식의 참(true)이면 반복을 계속, 거짓(false)이면 반복을 중단하고 for문을 벗어난다.

증감식

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

 

-1부터 5까지 세로로 한번, 가로로 한번 출력하는 예제

	public static void main(String[] args) { 
		for(int i=1;i<=5;i++)		//1부터 5까지 1씩증가
			System.out.println(i); // i의 값을 출력한다.

		for(int i=1;i<=5;i++)
			System.out.print(i);   // print()를 쓰면 가로로 출력된다.

		System.out.println();		
	}

 

중첩for문

-별찍기 예제

		for(int i = 1; i <= 5; i++) {
			for(int j = 1; j <= 10; j++) {
				System.out.print("*");
		}
		
		System.out.println();
        
//출력
**********
**********
**********
**********
**********

 

while문

while (조건식) { 
            // 조건식이 연산결과가 참(true)인 동안, 반복될 문장들을 적는다.
}
int i = 1; 	//초기화

while(i <= 10){	//조건식
    System.out.println(i);
    i++;	//증감식

 

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

System.out.println("========= for문 ==========");
		for(int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			System.out.println(i + " : " + ch);
		}
		
		System.out.println("======== while문 =========");
		int index = 0;
		while(index < str.length()) {
			char ch = str.charAt(index);
			System.out.println(index + " : " + ch);
			index++;
		}

 

-중첩while문을 이용한 구구단 출력하기

		int dan = 2;		//2단부터 시작해야하니 초기화값 설정
		while(dan < 10) {	//9단까지이니 10보다 작은 조건값 설정
			
			int su = 1;		//내부 while문에서 수의 초기화값 설정
			while(su < 10) {	
				System.out.println(dan + " * " + su + " = " + (dan * su));
				su++;
			}
			
			System.out.println();
			dan++;
		}

 

do-while문 

초기식;
do { 
     1회차에는 무조건 실행하고, 이후에는 조건식을 확인하여 조건을 만족하는 경우 수행할 구문(반복할 구문);
      증감식;
} while (조건식);
		Scanner sc = new Scanner(System.in);
		String str = "";
		do {
			System.out.print("문자열을 입력하세요 : ");
			str = sc.nextLine();
			System.out.println("입력한 문자 : " + str);
		
			/* 문자열(참조 자료형)은 == 비교가 불가능하다. String 클래스에서 제공하는 equals() 메소드를 통해 비교하자. */
		} while (!str.equals("exit"));
		
		System.out.println("프로그램을 종료합니다.");

 

break문

break문은 자신이 포함된 가장 가까운 반복문을 벗어난다. 

주로 if문과 함께 사용되어 특정 조건을 만족할 때 반복문을 벗어나게 한다.

		/* break문을 이용하여 무한루프를 활용한 1~100까지 합계 구하기 */
		int sum = 0;
		int i = 1;
		while(true) {		//무한루프, 생략불가
			sum += i;
			
			/* 반복문 조건과 별개로 반복문을 빠져나오기 위한 조건을 다시 작성 */
			if(i == 100) {
				break;
			}
			
			i++;
			
		}
		
		System.out.println("1부터 100까지의 합은 : " + sum + "입니다.");

 

continue문

break문과 달리 반복문을 벗어나지 않는다.

	public static void main(String[] args) {
		for(int i=0;i <= 10;i++) {
			if (i%3==0)
				continue;	//조건식이 참이 되면 6번줄 즉, 반복문의 블럭 끝으로 이동
			System.out.println(i);
		}					//여기
	}