Java

Program to find sum of natural numbers by getting input from user.

Program to find sum of natural numbers by getting input from user.
import java.util.Scanner;
public class demo1 {

    public static void main(String[] args) {

        int num, count, total = 0;

        System.out.println("Enter the value of n:");
        Scanner n = new Scanner(System.in);
        num = n.nextInt();
        n.close();
        for(count = 1; count <= num; count++){
            total = total + count;
        }

        System.out.println("Sum of first "+num+" natural numbers is: "+total);
    }
}
Nikhil Juneja

Passionate software developer and technical contributor at TutorialsLink.