JAVA

[ java ] 반복문

Adose 2024. 12. 3. 16:12

📌 반복문

  • 어떠한 것을 반복적으로 사용하고 싶을 때 자바에서는 반복문으로 while, do while, for문을 제공한다.

1️⃣ while문

  • while문은 탈출 조건식이 false를 반환할때 while문을 종료하게 된다.
while(조건문){
	 실행문;
	 
	 }
int i = 0;

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

 

 

📌 while문 무한루프

while(true){
System.out.println("hello");
}
  1. while(true)를 사용한다
  2. 조건문을 사용하여 빠져나온다.
    1. ex) break;

 

 

2️⃣ do-while 문

  • while문 과는 다르게 조건이 만족하지 않더라도 한번은 수행된다.
do{
	//반복할 문장들;
}while()
  1. do안에 있는 문장이 실행
  2. while안에 있는 조건이 만족되어야 → do 문장이 실행된다.

 

 

📌 while 사용 예시(10 이상을 입력하면 반복문에서 벗어난다.)

int value =0;

Scanner scan = new Scanner(System.in);
// scan 변수를 생성해준다.

	do {
		value = scan.nextInt();

		System.out.println("입력받은 값 : "+value);

		}while(value < 10);

System.out.println("반복문종료");

 

 

3️⃣ For 문

  • for 구문 자체에서 변수 초기화, 조건식, 증감식이 한줄로 표현된다.
  • for(변수 초기화 ; 조건식 ; 증감식)
for (int i=1 ; i<=100 ; i++)

 

 

📌 continue 사용

int total = 0;
		
for (int i=1 ; i<=100 ; i++) {
			if(i%2 != 0) {
				continue;
// continue를 만나면 아래쪽 문장들은 실행되지 않고 바로 다음으로 넘어간다.
// i%2!=0 은 홀수 일때를 말하는거라서 아래는 짝수의 합을 구하는 것이다. 
// 홀수를 만나면 다음으로 점프 
			}
			total = total+i;
			
		}
		
		System.out.println(total);

 

 

📌 break 사용

int total = 0;
		for (int i=1 ; i<=100 ; i++) {
			
			total = total+i;
			if(i==50) {
				break;
						}
		}
		
		System.out.println(total)

❗ continue 와 break 의 차이점

  • continue 를 사용할때 continue를 만나면 그 부분만 실행되지 않고 다시 올라간다
  • break를 사용할때는 break문을 만나면 실행이 종료된다.

 

 

4️⃣  For - each문

  • 객체의 크기만큼 반복 횟수를 정한다.
  • 임의로 반복 횟수를 정할 수는 없다.
int [] arr = {1, 2, 3, 4, 5} 

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

//for 함수를 아래와 같이 for-each문으로 사용할 수 있다. 
		for(int total:arr) {
			System.out.println(total);
			
		}