[java] Java method to sum any number of ints

I need to write a java method sumAll() which takes any number of integers and returns their sum.

sumAll(1,2,3) returns 6
sumAll() returns 0
sumAll(20) returns 20

I don't know how to do this.

This question is related to java sum

The answer is


You could do, assuming you have an array with value and array length: arrayVal[i], arrayLength:

int sum = 0;
for (int i = 0; i < arrayLength; i++) {
    sum += arrayVal[i];
}

System.out.println("the sum is" + sum);

I hope this helps.


import java.util.Scanner;

public class SumAll {
    public static void sumAll(int arr[]) {//initialize method return sum
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        System.out.println("Sum is : " + sum);
    }

    public static void main(String[] args) {
        int num;
        Scanner input = new Scanner(System.in);//create scanner object 
        System.out.print("How many # you want to add : ");
        num = input.nextInt();//return num from keyboard
        int[] arr2 = new int[num];
        for (int i = 0; i < arr2.length; i++) {
            System.out.print("Enter Num" + (i + 1) + ": ");
            arr2[i] = input.nextInt();
        }
        sumAll(arr2);
    }

}

If your using Java8 you can use the IntStream:

int[] listOfNumbers = {5,4,13,7,7,8,9,10,5,92,11,3,4,2,1};
System.out.println(IntStream.of(listOfNumbers).sum());

Results: 181

Just 1 line of code which will sum the array.


public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
    int sum = 0; //start with 0
    for(int n : nums) { //this won't execute if no argument is passed
        sum += n; // this will repeat for all the arguments
    }
    return sum; //return the sum
} 

Use var args

public long sum(int... numbers){
      if(numbers == null){ return 0L;}
      long result = 0L;
      for(int number: numbers){
         result += number;
      }
      return result;   
}

 public static void main(String args[])
 {
 System.out.println(SumofAll(12,13,14,15));//Insert your number here.
   {
      public static int SumofAll(int...sum)//Call this method in main method.
          int total=0;//Declare a variable which will hold the total value.
            for(int x:sum)
          {
           total+=sum;
           }
  return total;//And return the total variable.
    }
 }