반복문
1. while
2. for
- while, for문은 서로 바꿔 쓸 수 있다
1. while
1) 초기화: int x = 0;
2) while문: while( 조건 ){ (조건 만족시 출력); 증감식 }
예) int i = 0
while(i < 9){ ("출력물"); 증감식 }
1) 초기화: int x = 0;
2) while문: while( 조건 ){ (조건 만족시 출력); 증감식 }
예) int i = 0
while(i < 9){ ("출력물"); 증감식 }
※ do-while문과 차이점: do-while문은 일단 한 번은 구문이 작동을 함
while문은 조건 따져보고 만족하면 구문이 작동
while문은 조건 따져보고 만족하면 구문이 작동
2 for
- for문 안에 초기화식, 범위, 증감식 포함
예)
예) 두 수를 입력받고 두 수의 합을 구하기(1,10)
※ break, continue
예)
public class Ex05_for05 {
public static void main(String[] args){
// 각 단의 단수가 짝수면 짝수만 곱하고
// 각 단의 단수가 홀수면 홀수만 곱하도록 구구단을 출력하라
for(int i = 2; i <= 9; i++){
System.out.println();
System.out.printf("%d단입니다%n", i);
for(int j = 1; j <= 9; j++){
if(i % 2 == j % 2){ // <- 이 줄 추가로 해결
System.out.printf("%d X %d = %d%n", i, j, (i*j));
}// for문 내 if문
}// 내부 for문
}// 외부 for문
}// end of main
}// end of class
| cs |
예) 두 수를 입력받고 두 수의 합을 구하기(1,10)
public class Example3 {
public static void main(String[] args){
if(args.length !=2){
System.out.println("입력해야할 인자값은 두 개이어야 합니다");
return;
}//유효성 검사
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int e;
int sum = 0;
if(a > b){
e = b;
b = a;
a = e;
}else if(a==b){
System.out.println("입력한 값이 같습니다.");
return;
}
for(int i = a; a <= b; a++){
sum += a;
}
System.out.println(args[0]+" ~ "+args[1]+"의 합은 "+sum+"입니다.");
}// end of main
}// end of class
| cs |
※ for문을 2개 작성해야하는 것을 1개로 줄여서 표현 - 효율성 확보
임시변수를 하나 더 만들어야한다는 점을 착안! - 아주 중요!
※ break, continue
예)
public class BreakTest{
public static void main(String[] args){
int inputData = Integer.parseInt(args[0]);
int i = 0;
int sum = 0;
while(true){ //무한 반복문이고 구문 뒤에 출력문이 있는데도 에러가 발생하지 않는다?
i++;
sum = sum+i;
if(i==inputData){ // 에러가 발생하지 않는 이유는 여기서 빠져나갈 구멍을 마련해 놓았기 때문이다
break;
}//end of if
}//end of while
System.out.println("0~"+inputData+"까지의 합은 : "+sum+"입니다.");
for( ; ; ){ //enhanced for loop
i++;
sum += i;
if(i==inputData){
break;
}// while문을 for문으로 전환
}// for문을 이용한 무한 반복문 >> i가 inputData와 같아지면 빠져나와서 출력
System.out.println("0~"+inputData+"까지의 합은 : "+sum+"입니다.");
}// end of main
}// end of class
| cs |