[TIL_JAVA] 반복문

HKS·2020년 12월 17일
0

기초문법

목록 보기
8/8

1. 반복문이란

특정 조건에 따라 반복적으로 진행

  • for/while문 : 조건이 참일 때까지 반복 수행

2. for 문

for(int i = 0; i < 5; i++) {}
i가 1부터 5보다 작을 때 까지 i에 1씩 더해가며 진행

package basicGrammar;

import java.util.Scanner;

public class Variable {

	public static void main(String[] args) {
		System.out.print("숫자를 입력해주시오 : ");
		Scanner inputData = new Scanner(System.in);
		int result = inputData.nextInt();
		
		for (int i = 1; i < 5; i++) {
			System.out.printf("%d * %d = %d \n", result, i, (result * i));
		}
		inputData.close();
	}
}
출력
숫자를 입력해주시오 : 8
8 * 1 = 8 
8 * 2 = 16 
8 * 3 = 24 
8 * 4 = 32 

3. while문

while(num1 < 10) {}
num1이 10보다 작을때 까지 진행(true일 때)
조건식이 false가 되면 반복 멈춤

package basicGrammar;

import java.util.Scanner;

public class Variable {

	public static void main(String[] args) {
		System.out.print("숫자를 입력해주시오 : ");
		Scanner inputData = new Scanner(System.in);
		int result = inputData.nextInt();
		int i = 1;
		
		while (i < 5) {
			System.out.printf("%d * %d = %d \n", result, i, (result * i));
			i++;
		}
		
		inputData.close();
	}
}
출력
숫자를 입력해주시오 : 4
4 * 1 = 4 
4 * 2 = 8 
4 * 3 = 12 
4 * 4 = 16 

4. do~while문

while문과 비슷하지만 조건 결과에 상관없이 무조건 최초 한번은 {...} 수행 후
while의 조건식이 true면 do의 {...}반복 수행

package basicGrammar;

public class Variable {

	public static void main(String[] args) {
		do {
			System.out.println("조건 상관없이 1번은 실행");
		} while (false); //while문이 true만 실행
	}
}
출력
조건 상관없이 1번은 실행
profile
하루 한 줄이라도

0개의 댓글