Sum Of First "n" Natural Numbers | Java Programs

Output:

*** Sum of Natural Numbers ***

Enter the value of n: 10
Sum of first 10 natural numbers is: 55

Click Here For Java Online Compiler

Solution:

import java.util.Scanner;

public class SumOfNNaturalNums {

    public static void main(String[] args) {

        int num = 0;
        int total = 0;

        System.out.println("*** Sum of Natural Numbers ***" + "\n");
        System.out.print("Enter the value of n: ");
        Scanner scan = new Scanner(System.in);
        num = scan.nextInt();
        for (int i = 1; i <= num; i++) {
            total = total + i;
        }
        System.out.println("Sum of first " + num + " natural numbers is: " + total);
    }
}
Share This :

Related Post



sentiment_satisfied Emoticon