How to find the sum of numbers from an array in java?


I'm trying to get the sum of all the numbers.

For example:

public static void testArray() {
    int myArray[] = {3, 5, 7, 12};
    for (int i = 0; i < myArray.length; i++) {
        int i2 = i + 1;
        if (i2 >= myArray.length - 1) {
            i2 = 0;
            i2 = 0;
        }
        int sum = myArray[i] + myArray[i2];
        System.out.println(sum);
    }
}

Yes, yes, I know that this code is a piece of nonsense that does not even come close to fulfilling its function, but I have already broken my head and I am far from a mathematician (and not a programmer).

How do I find the sum of the numbers in an array, provided that the length of the array can be arbitrary, and the numbers in it are different, not having any sequence?

Author: silksofthesoul, 2011-09-03

9 answers

Honestly didn't understand the question. In the beginning it says-I'm trying to get the sum of some numbers... and what does some mean?? If there are all numbers, then it is very simple to do:

public static void testArray() {
    int myArray[] = {3, 5, 7, 12};
    int sum = 0;
    for (int i = 0; i < myArray.length; i++) {
        sum = sum + myArray[i];
    }
    System.out.println(sum);
}
 18
Author: Grimon, 2020-12-02 14:35:23

In Java 8, you can use stream{[6 in 1 line]}

int myArray[] = {3, 5, 7, 12};
int total = IntStream.of(myArray).sum();

Similarly, you can use the class Arrays

Arrays.stream(myArray).sum() 

The stream method has overloads for primitive types and a generalized form, which is suitable for arrays of other types.

 17
Author: NikolayK, 2017-08-07 08:42:10

There are several ways to find the sum of elements in an array:

  • Using the Java 8 Stream API (first using the method Arrays::stream convert the array to a stream of integers, then get the sum of this stream by the method Stream::sum)

    int array[] = {3, 5, 7, 12};
    int sum = Arrays.stream(array).sum();
    
  • Cycle by elements (for-each cycle)

    int array[] = {3, 5, 7, 12};
    int sum = 0;
    for (int element : array)
        sum += element;
    
  • Loop with using indexes

    int array[] = {3, 5, 7, 12};
    int sum = 0;
    for (int i = 0; i < array.length; ++i)
        sum += array[i];
    

Online code examples:

 3
Author: diralik, 2020-12-02 13:50:56
/**
 * Sum of all elements from 1 to 1000
 */
final int sum = Stream.iterate(1, n -> n + 1).limit(1000).mapToInt(el -> el).sum();
 0
Author: Jackkobec, 2019-03-14 00:50:16
public class test {
    public static int[] myArray;
    public static void main(String[] args) {
        int myArray[] = {3, 5, 7, 12};
        System.out.print(sum(myArray));
    }
    public static int sum(int[] arr) {
        return sum(arr, 0, 0);
    }
    public static int sum(int[] arr, int sum, int count) {
        sum += arr[count];
        if (count < arr.length - 1) return sum(arr, sum, count + 1);
        return sum;
    }
}
 0
Author: Yosef Gorbov, 2020-12-02 14:05:15
for (int i = 0; i < arraySize; i++) {
    numbers[i] = numberOfArrayElements.nextInt();
    sum = sum + numbers[i];
}
 0
Author: polar, 2020-12-02 14:14:59

Counting the sum of two numbers. If it is, we return TRUE:

public class moed2AQuation2A2015 {
    public static void main(String args[]) {
        int arr[] = {-2, 3, 5, 7, 12};
        System.out.println(sum2(arr, 19));
    }

    public static boolean sum2(int[] arr, int num) {
        return sum2(arr, num, 0, arr.length - 1);
    }

    public static boolean sum2(int[] arr, int n, int first, int second) {
        int summa = arr[first] + arr[second];
        if (summa == n) return true;
        if (second < first && first == second) return false;
        if (first < arr.length - 1 && second != first)
            return sum2(arr, n, first, second - 1) || sum2(arr, n, first + 1, second);
        else return false;
    }
}
 0
Author: Yosef Gorbov, 2020-12-02 14:15:04
/**
 * calculate sum of  the array
 */
public static void main(String[] args) {
    int myArray[] = {3, 5, 7, 12};
    System.out.print(sum(myArray));
}

public static int sum(int[] arr) {
    return sum(arr, arr.length - 1);
}

public static int sum(int[] arr, int n) {
    if (n == 0)
        return arr[0];
    else
        return arr[n] + sum(arr, n - 1);
}
 0
Author: Yosef Gorbov, 2020-12-02 14:15:10

Here are 3 ways, from the most primitive, to the normal. Don't criticize too much, I'm just learning.

import java.util.Arrays;

// сумма всех элементов массива, способ первый
class BlaBlaBla1 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int sum = 0;

        for (int i = 0; i < nums.length; i++) sum += nums[i];
        System.out.println("1ый способ = " + sum);
    }
}

// сумма всех элементов массива, способ второй
class BlaBlaBla2 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int sum = 0;

        sum = Arrays.stream(nums).sum();
        System.out.println("2ой способ = " + sum);
    }
}

// сумма всех элементов массива, способ третий: FOR-EACH
class BlaBlaBla3 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int sum = 0;

        for (int x : nums) sum += x;
        System.out.println("3ий способ = " + sum);
    }
}
 0
Author: Lamardinho, 2020-12-02 14:23:01