본문 바로가기

[TIL] while 문

인포꿀팁 발행일 : 2020-07-24

오늘 배운 내용은 while 문

 

조건식을 먼저 비교하여 조건식이 참인 경우 특정 영역을 반복 수행하는 문장이다.

조건식이 false이면 while문을 빠져나온다.

예제1) 1부터 100까지의 합을 구하기

전위 후위형 연산자 사용에 유의해야한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package ex0724;
 
public class whileEx2 {
 
    public static void main(String[] args) {
        int s, n;
        
        s=0;
        n=0;
        while(n<100) {
            n++;     //n:1 2 3 4  5 ..  100
            s+=n;    //s:1 3 6 10 15.. 5050
        }
        System.out.println(n+"결과:"+s);//100번 5050
    }
 
}
 
cs

 

예제2)

처음 조건이 false면 while문 안의 내용이 출력되지 않는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package ex0724;
 
public class whileEx4 {
 
    public static void main(String[] args) {
        int n;
        n=10//처음 조건이 false면 while문 안의 내용이 출력되지 않는다.
        while(n<10) {
            n++;
            System.out.println("안:"+n);
        }
System.out.println("밖:"+n);
    }
 
}
//출력값: 밖:10
 
cs

 

예제3)

10! 값 구하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package ex0724;
 
import java.util.Scanner;
 
public class whileEx6 {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int s, n;
        s = 1;
        n = 0;
        while (n < 10) {
            n++;
            s *= n;
        }
        System.out.println(n + "," + s);
        sc.close();
    }
 
}
//10! 값 구하기: 10,3628800
cs

 

예제4)

num의 숫자 까지의 합을 구하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package ex0724;
 
import java.util.Scanner;
 
public class whileEx7 {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int s, n, num;
        
        System.out.print("정수?");
        num = sc.nextInt();
        s=n=0;
        while(n<num) {
            n++;
            s+=n;
        }
        System.out.println("1~"+num+"까지 합:"+s);
        sc.close();
    }
 
}
//num 의 숫자 까지의 합을 구하기ㅁ
cs

예제5)

1+ (1+2) + (1+2+3)+(1+2+3+4) .....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package ex0724;
 
 
public class whileEx9 {
 
    public static void main(String[] args) {
        
        int s1, s2, n;
        //1+ (1+2) + (1+2+3)+(1+2+3+4) .....
        s1 = s2 =n=0;
        while(n<10) {
            n++;
            s1+=n;
            s2+=s1;
        }
        System.out.println(s2);
    }
 
}
 
cs

 

 

'Language > JAVA' 카테고리의 다른 글

[TIL] for문  (0) 2020.07.27
[TIL] do-while 문  (0) 2020.07.27
[TIL]switch - case 문  (0) 2020.07.24
[TIL] if문 예제 풀이  (0) 2020.07.23
[TIL] if문  (0) 2020.07.23

댓글