본문 바로가기
💻 하나씩 차곡차곡/자료구조 & 알고리즘(JAVA)

while문 사용하여 1부터 n까지 정수의 합 구하기 (chap01/SumWhile)

by 뚜루리 2022. 10. 6.
728x90
320x100
package chap01;

import java.util.Scanner;

public class SumWhile {

    //while 문으로 1,2,... n의 합을 구함

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("1부터 n까지의 합을 구합니다.");
        System.out.print("n값 : "); int n = scan.nextInt();

        int sum = 0;
        int i  = 1;

        while (i <= n){
            sum += i;
            i++;
        }

        System.out.println("1부터 " + n + "까지의 합은 " + sum + " 입니다.");


    }
}

보통 for문을 사용하긴 하지만, while문을 사용한다면 이렇게...!

728x90
320x100