on Leave a Comment

Java Program to Calculate the Sum of Natural Numbers

This java program calculates the sum of natural numbers. First you have to ask "How many numbers do you want to enter?" and then read all numbers and store the sum of all number in a variable.

Java Program to Calculate the Sum of Natural Numbers

import java.util.Scanner;

class SumNum
{
 public static void main(String[] args) {
  System.out.print("How many numbers do you want to enter?   ");
  int n, sum = 0;
  Scanner sc = new Scanner(System.in);
  n = sc.nextInt();
  for(int i = 0; i<n; i++)
  {
   System.out.print("Enter "+(i+1)+" number : ");
   sum = sum + sc.nextInt();
  }
  System.out.println("Sum of all number is "+sum);

 }
}

Output:

How many numbers do you want to enter?   5
Enter 1 number : 1
Enter 2 number : 8
Enter 3 number : 7
Enter 4 number : 4
Enter 5 number : 5
Sum of all number is 25

0 comments:

Post a Comment