Java program to find the sum of n natural numbers

Java Programming Java8Java Technologies Object Oriented Programming

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
raja
Published on 25-Apr-2018 15:25:03
Advertisements