**Sum of n numbers in java** program is very easy and simple in which we take N numbers and perform addition.

This programs performs sum of the N numbers.

**Sum of n numbers formula**

Suppose numbers 1,2 ,3..N

Sum = 1+2+3….+N

**Example : **

Suppose we have the 4 numbers as 10, 20, 30, 40

Sum of N numbers will add all 4 numbers = 10 + 20 + 10 + 10

Sum of 4 numbers is = 50

**Logic to implement sum of N number program :**

We take the N from user that is how many number user want to add next. After that using for loop we take N number input from user and simultaneously we add number user enters.

**Algorithm :**

- Start
- Declare variables
- Take N number from user
- Take number one by one till N input from user
- Perform addition
- print sum
- End

## Program for sum of n numbers

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.*; public class Main { public static void main(String[] args) { int n, sum = 0, c, value; Scanner sc=new Scanner(System.in); System.out.println("How many numbers you want to add?"); n=sc.nextInt(); System.out.println("Enter "+n+" integers"); for (c = 1; c <= n; c++) { value=sc.nextInt(); sum = sum + value; } System.out.println("Sum of the integers = "+sum); } } |

**Output : **

**Explanation :**

**1. Declare the variables**. int n => to store N values, sum = 0 => to store addition of N numbers, c => to store iterative value and value => to store the Nth value user enters.

**2. Next take N value user want to add . and store it in n.**

**3. Now using for loop take a 4 number from user** and store that input in value now we have value so perform addition and store it in sum.

**4. For example :**Suppose N = 3 now at next statement for (c = 1; c <= n; c++)

**At Iteration 1: **

c=1 and condition 1<= 3 becomes true and executes the for blockscanf(“%d”, &value) => 10sum = sum + value => sum=10

**At Iteration 2: **

c=2 and condition 2<= 3 becomes true and executes the for block

scanf(“%d”, &value) => 10

sum = sum + value => sum=20

**At Iteration 3: **

c=3 and condition 3<= 3 becomes true and executes the for block

scanf(“%d”, &value) => 10

sum = sum + value => sum=30

**At Iteration 4: **

c=4 and condition 4<= 3 becomes false and execution of the for block skipped.

**5. Now we have the sum of N numbers in sum variable.**

**6. So print the value sum=30**

## Leave a Reply