Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method to sum any number of ints

Tags:

java

sum

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.

like image 533
browngirl Avatar asked Jun 16 '13 05:06

browngirl


People also ask

Is there any sum method in Java?

sum() is a built-in method in java which returns the sum of its arguments. The method adds two integers together as per the + operator.

What does sum += do in Java?

sum = sum + 10 ; This kind of operation is very common (where 10 is replaced by whatever value you want). It's so common that Java has a shorter way of saying the same thing. Java uses the compound addition assignment operator, which looks like: += (plus sign, followed by equal sign).

How do you sum values in Java?

So you simply make this: sum=sum+num; for the cycle. For example sum is 0, then you add 5 and it becomes sum=0+5 , then you add 6 and it becomes sum = 5 + 6 and so on.


3 Answers

You need:

public int sumAll(int...numbers){

    int result = 0;
    for(int i = 0 ; i < numbers.length; i++) {
        result += numbers[i];
    } 
    return result;
}

Then call the method and give it as many int values as you need:

int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);
like image 166
Azad Avatar answered Oct 23 '22 13:10

Azad


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.

like image 39
Gabriel Avatar answered Oct 23 '22 13:10

Gabriel


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
} 
like image 36
Bhesh Gurung Avatar answered Oct 23 '22 13:10

Bhesh Gurung