Home Lifestyle Sum of N Natural Numbers in Java Language

# Sum of N Natural Numbers in Java Language

0
82

Sum of N Natural Numbers in Java Language – We have to develop a Java program to calculate the sum of n natural numbers. Sum of natural number N as given as sum = 1+2+3+….+N

• Examples:-
• 1+2+3+4+5 = 15
• 1+2+3+4+5+6+7+8+9+10 = 55

``````import java.util.Scanner;

public class NaturalNumberSum {

// method to find sum of N natural numbers
public static int naturalNumberSum(int number){

int i = 1; // iterator variable
// variable to store sum value
int sum = 0;

// loop to repeat the process
while (i<=number) {

sum = sum + i;
// increase iterator variable
i++;
}

// return sum value
return sum;
}

public static void main(String[] args) {

// declare variables
int number = 0;
int sum = 0;

// create Scanner class object
Scanner scan = new Scanner(System.in);

System.out.print("Enter N value:: ");
number = scan.nextInt();

// Calculate the sum value
sum = naturalNumberSum(number);

// display result
System.out.println("Sum = "+sum);

// close Scanner class objects
scan.close();
}
}

``````

The output for different test-cases:-

``````

Enter N value:: 5
Sum = 15

Enter N value:: 10
Sum = 55

``````