Java program to find the sum of n natural numbers



Create a new variable sum, initialize it with 0. Add it to the 1st element, repeat this up to n (where n is given) using loops.

Example

import java.util.Scanner;
public class SumOfNNumbers {
   public static void main(String args[]){
      int sum = 0;
      System.out.print("Enter the number value:: ");
      Scanner sc = new Scanner(System.in);
      int num = sc.nextInt();

      for (int i = 0; i<num; i++){
         sum = sum +i;
      }
      System.out.println("Sum of numbers : "+sum);
   }
}

Output

Enter the number value::
50
Sum of numbers : 1225

Advertisements