본문 바로가기

건승하고있어요/알고리즘

[for문] n의 합

반응형

문제: n이 주어졌을 때 1부터 n까지의 합을 구하는 프로그램을 만들어라

(출처:https://www.acmicpc.net/problem/8393)


N 예외처리 한거 빼면 포문 단 3줄에 해결할 합 문제.

귀찮음이 cnt를 불러왔습니다. 핰


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.Scanner;
 
public class Sum2 {
    
    public static void main(String[] args) {
        
        Scanner scan = new Scanner(System.in);
        int N = scan.nextInt();
        boolean YN = true;
        
        while(YN) {
            if(N<1 || N>10000) {
                System.out.println("다시 입력해 주세요");
                N = scan.nextInt();
            }else {
                YN = false;
            }
        }
        
        int cnt=0;
        for(int i=0 ; i<=N ; i++) {
            cnt = cnt+i;
        }
        
        System.out.println(cnt);
    }
 
}
 
cs


반응형