개발자 미니민의 개발스터디

10. while 문

by mini_min

◾ while 문 조건이 만족하는 경우에 계속 돌아간다.

처음부터 while 문 조건이 만족하지 않는 경우, while 안의 문장은 실행되지 않는다.

n = 0; // 반드시 초기화 필요
//		// 초기값이 없는 상태에서 문장 실행이 안됨
//
while (++n < 10) {
System.out.print(n + "  ");
}

 

◾ while 문 안에 if 조건문을 넣을 수 있다.

char c;
int n = 0;

c = 'A';

while (c < 'Z') {
    System.out.print(c + "\t");
    n++;
    if(n%7 == 0) {  // n이 7번째가 되는 순간까지는 if가 false니까 실행안한다. 
        System.out.println();
    }

// ???????????????????????????????????
    c++;
}

 

◾ 증감식을 while 문 조건식 안에 넣을 수 있다.

int s, n;
s = 0;
n = 0;
while(++n < 10) {	// 1,2,3,4,5,6,7,8,9 까지만 함. ++를 먼저 하기 때문에!
    s+=n;
}
    System.out.println("결과 : " + s);
    System.out.println(n);

 

◾ 1~100 까지 홀수 합

int n, s;
n = 1;
s = 0;
while(n<100) {
    s+=n;
    n+=2;

}
System.out.println("결과 : " + s);

 

◾ 정수를 입력 받아서 입력 받은 정수까지의 홀수 합 구하기

Scanner sc = new Scanner(System.in);
int num, s, n;

System.out.print("양수 ? ");
num = sc.nextInt();

n = 1;
s = 0;

while(n <= num) {  // <= 100은 짝수라서 =을 안넣은 것.
    s += n;
    n += 2;

}

System.out.println(num + "까지의 정수의 홀수 합 ? " +s);

sc.close();

 

◾ while문으로 구구단 만들기

Scanner sc = new Scanner(System.in);
int dan, n;

System.out.print("단 ? ");
dan = sc.nextInt();

n = 0;
while(n < 9) {
    n++;
    System.out.printf("%d * %d = %2d\n", dan, n, dan*n);

}


sc.close();

 

◾ 1/2 + 2/3 + ... 9/10 의 결과는?

double a, b, s;

a = 1;
b = 0;
s = 0;

while(a <10) {
    a++;
    b = a - 1;
    s+= (b/a);
}

    System.out.println("결과는 : " + s);

 

◾1~100 까지 수중 홀수를 한 줄에 5개씩 출력하고 마지막에 홀수합 출력

int n, s, cnt;
n = 1;
s = 0;
cnt = 0;

while(n < 100) {
    s+= n;
    System.out.print(n + "\t");
    cnt++;	//  위치(자리) 를 나타내는 변수 만들어주는게 속 편하다. 

    if(cnt%5 ==0) {
        System.out.println();
    }

    n+= 2;

}

System.out.println("\n홀수 합 : "+ s);

 

◾ 1~100 까지 수중 3또는 4의 배수를 제외한 수를 한 줄에 5개씩 출력.

int n, cnt;

n = 0;
cnt = 0;

while(n < 100) {
    n++;
    if(n%3 !=0 && n%4 !=0) {

    System.out.print(n + "\t");

    cnt++;

    if(cnt%5==0) System.out.println();

    }


}

 

◾ while 문의 무한루프를 빠져나오려면 break 를 사용해야한다.

int n, s;

s = n = 0;
while(true) {	// 무한루프
    n++;
    s+=n;
    if(n>=10) {
        break;	//while문을 빠져 나감.
    }
}
System.out.println("결과: " +s);

 

◾ 정수를 입력 받아 1부터 입력 받은 수까지의 합, 짝수 합, 홀수 합 구하기

Scanner sc = new Scanner(System.in);
int n, num;
int s1, s2, s3;

s1 = s2 = s3 = 0;

System.out.print("수 ? ");
num = sc.nextInt();

n = 0;
while(n < num) {
    n++;
    s1 += n;
}

n = 0;
while(n <= num) {
    s2 += n;
    n += 2;
}

n = 1;
while(n <= num) {
    s3 += n;
    n += 2;
}

 

◾ 두 정수를 입력 받아 입력 받은 수중 적은 수에서 큰수까지의 합 구하기

Scanner sc = new Scanner(System.in);

int a, b, s, temp;

s = 0;
temp = 0;

System.out.print("두수 ? ");
a = sc.nextInt();
b = sc.nextInt();

if(b>a) {
    temp = b;
    b = a;
    a = temp;
    temp = b;
}


while(b <= a) {
    s += b;
    b++;

}
System.out.println(temp + " ~ " + a + "까지의 합 = " + s);

 

◾ 1+2+4+7+11+... 의 20번째 항까지 합을 구하는 프로그램.

int n, s, ss;

n = 1;
s = 1;
ss = 1;

while(n < 20) {
    s += n;
    n++;
    ss += s;
}


System.out.println("결과 : " + ss);

 

◾ 피보나치수열

1+1+2+3+5+8+13+21 ...

x = 1;
y = 1;
t = 0;
ss = 1+1;

n = 0;

while(n < 6) {
    t = x + y;
    ss += t; // 1+1+2
    x = y; // 1
    y = t; // 2
    n ++; 

    // t = 3
    // ss += t 는 1+1+2+3...

}

 

◾ while 문에서 break 는 while, do~while, for, switch~case 에서 사용 가능하다

제어문을 빠져나올 수 있다.

가령, 무한 루프 while 문에서 if 조건문에 해당되는 경우 break 로 while 문장을 빠져나올 수 있다.

int n, s;
n = s = 0;

// 1~n까지 합이 1000이 넘는 최초의 수와 합을 출력
while(true) {
    n++;
    s+=n;
    if(s>1000) {
        break;
    }
}
System.out.println("수 : " + n);
System.out.println("합 : " + s);

 

◾ break : 실수를 입력 받는데 입력 받은 수가 0 이하라면 종료하기

Scanner sc = new Scanner(System.in);

double n, s;
s = 0;

System.out.println("실수는 ? ");
while(true) {
    n = sc.nextDouble();
    if(n <= 0.0) {
        break;
    }
    s += n;
}
System.out.println("결과: " + s);

sc.close();

 

◾ break 에서 특정 위치로 이동할 수 있음!

gogo:
for(int i=1; i<=3; i++) {
    for(int j=1; j<=3; j++) {
        if(i+j == 4) {
            break gogo;
        } System.out.println("i: " +i+ ", j: " +j);
    }	
}

 

◾ break 가 반복문을 아예 빠져나오는 거라면, continue 는 반복문을 빠져나오지 않고 continue 아래 문장은 실행하지 않고 다시 반복문 위로 실행되도록 하는 키워드다.

정수를 입력 받아 입력 받은 수중 짝수만 합 구하기

Scanner sc = new Scanner(System.in);
int n, s;

s = 0;
System.out.print("입력 수[0:종료] ");
while(true) {
    n = sc.nextInt();
    if(n <= 0) {
        break;
    }
    if(n%2==1) {
        continue;
    }

    s += n;

}

System.out.println("합: " + s);

 

◾ 5개의 실수를 입력 받아 0보다 큰수의 합 구하기

Scanner sc = new Scanner(System.in);

double input, s;
s = 0;

System.out.println("5개의 실수는? ");
for(int i=0; i<5; i++) {
    input = sc.nextDouble();

    if (input <= 0) {
        continue;
    }

    s += input;

}

System.out.println("합: " + s);

 

◾ continue 도 특정 위치로 점프할 수 있다!

jump:
for(int i=1; i<=3; i++) {
    for(int j=1; j<=3; j++) {
        if(i+j==4) {
            continue jump;
        }
        System.out.println("i: " + i + " j: " + j);
    }

// 1,1 / 1,2 / 2, 1
}

 

◾ 정수를 입력 받아 1에서 받은 수까지 합 구하기 (단, 1 미만이나 1000 이상 정수는 x)

Scanner sc = new Scanner(System.in);

int n, s;
s = 0;
n = 0;


// 1 미만이나 1000 이상인 경우에만 계속 원하는 정수 입력하기 
do {
    System.out.print("수 ? ");
    n = sc.nextInt();
} while(n < 1 || n > 1000); 



for(int i=0; i<=n; i++) {
    s += i;
}

System.out.printf("1~%d까지 합 : %d", n, s);

 

◾ 2개 정수를 입력 받아, 수중에서 적은 수에서 큰 수 사이에 3의 배수이거나 5의 배수인 수들의 합과 평균을 구한다.

Scanner sc = new Scanner(System.in);

int n1, n2, temp;
int s = 0;
int cnt = 0; // s 나누기 cnt 


System.out.print("두정수 ? ");
n1 = sc.nextInt();
n2 = sc.nextInt();

if(n2>n1) {
    temp = n2;
    n2 = n1;
    n1 = temp; 	// n1이 큰 값됨.
}

for(int i=n2; i<=n1; i++) {
    if(i%3==0||i%5==0) {
        s += i;
        cnt++;
    }

}


System.out.println("합: " + s);
System.out.println("평균: " + (s/cnt));

 

◾ 1~100까지 수중 4와 6의 공배수를 출력하시오

4와 6의 최소공배수는 12

for(int i=1; i<=100; i++) {
    if(i%12==0) {
        System.out.print(i+ " ");
    }
}

 

◾ return !! : 리턴의 경우 main 메소드를 빠져나간다. 

main 메소드를 빠져나간다고 해서 프로그램이 무조건 종료되는 것은 아니다. 하지만, main 을 빠져나가서 다른 할 일(?) 이 없는 경우에는 프로그램이 죽는다. (종료)

 

아래 코드에서는 1 이상 정수를 입력하지 않았기 때문에 프로그램이 죽어버렸다. 

Scanner sc = new Scanner(System.in);

// 정수를 입력 받아 1에서 입력 받은 수까지 합 구하기
// 단, 입력 받은 수가 1미만 이면 프로그램 종료

int n, s;

System.out.print("수 ? ");
n = sc.nextInt();
if(n<1) {
    System.out.println("1이상의 수를 입력 해야합니다.");
    sc.close();
    return; // main 메소드를 빠져나감 (메인 빠져나간다고 무조건 프로그램 종료는 아님)
            // 여기서는 할 일이 없어서 죽음 (main이)
}


s = 0;
for(int i = 1; i <=n; i++) {
    s += i;
}
System.out.println("1~" + n + "까지 합 : " + s);

 

 

 

 

 

'개발 공부중 > 📑 코드 복습' 카테고리의 다른 글

12. Array 2차원 배열 + 퀴즈  (0) 2023.02.24
11. Array 배열 + 퀴즈  (0) 2023.02.24
* 연산 퀴즈  (0) 2023.02.23
9. for 문  (0) 2023.02.22
8. switch case 문  (1) 2023.02.22

블로그의 정보

개발자 미니민의 개발로그

mini_min

활동하기