Java method for summing any number of ints

I need to write the 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 do not know how to do that.

+8
java sum
source share
7 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); 
+13
source share

If you are using Java8, you can use 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

Only 1 line of code that sums the array.

+12
source share
 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 } 
+9
source share

Use var args

 public long sum(int... numbers){ if(numbers == null){ return 0L;} long result = 0L; for(int number: numbers){ result += number; } return result; } 
+2
source share
 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); } } 
+1
source share
  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. } } 
0
source share

You can do it if you have an array with the value and length of the array: arrayVal[i] , arrayLength :

 int sum = 0; for (int i = 0; i < arrayLength; i++) { sum += arrayVal[i]; } System.out.println("the sum is" + sum); 

Hope this helps.

0
source share

All Articles