How to Find the Sum of All the Numbers in an Array in Java

Java/ Sum of any two values in an array of numbers

Should I make another array to storage sum of any two elements?

If it is required to provide only the number of the pairs equal to the given number, array is not required, simple if statement allows to check the condition and increment the counter (and print the pair if needed):

if (a[i] + a[j] == x) {
pairs++;
System.out.println("Found a pair: " + a[i] + " + " + a[j]);
}

What kind of method use to get the sum of any two elements in the array?

Two nested loops:

for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++) {
//...
}
}

How list the number of combinations?

The total number of possible pairs is calculated by the formula of decreasing progression from n - 1 to 1: S = n * (n - 1) / 2, so for n = 5 it is 5 * 4 / 2 = 10.

The number of matching pairs is simply counted in the innermost loop.

Sum all the elements java arraylist

Two ways:

Use indexes:

double sum = 0;
for(int i = 0; i < m.size(); i++)
sum += m.get(i);
return sum;

Use the "for each" style:

double sum = 0;
for(Double d : m)
sum += d;
return sum;

Finding the sum of numbers in an array - excluding the number 13 and the number directly after it

Well, you use i as iterator. just make i++ when the current number is 13. This way, not only you don't add 13 to the sum but you also skip the next value.

public int sum13(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
// we start by adding all the non-13s to the sum
if (nums[i] != 13){
sum += nums[i];
}
else {
i++;
}
}
return sum;
}

How to perform a sum of an int[] array

Your syntax and logic are incorrect in a number of ways. You need to create an index variable and use it to access the array's elements, like so:

int i = 0;        // Create a separate integer to serve as your array indexer.
while(i < 10) { // The indexer needs to be less than 10, not A itself.
sum += A[i]; // either sum = sum + ... or sum += ..., but not both
i++; // You need to increment the index at the end of the loop.
}

The above example uses a while loop, since that's the approach you took. A more appropriate construct would be a for loop, as in Bogdan's answer.

Find the sum of custom number of elements in an array of Integers

Use Stack (recursively) to find the array elements which will sum to the desired target within the required array elements limit. Doing it this way will actually find all combinations but only those which use fall on the elements limit are placed into a List.

Please read the comments in code. Delete them later if you like. Here is a runnable to demonstrate this process:

package sumtargetlimit_demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

public class SumTargetLimit_Demo {

// The desired Target Sum
private int targetSum = 20;

/* The max allowable array elements to use in order to acquire
the desired Target Sum. */
private int numbersLimit = 3;

// A Stack to hold the Array elements which sum to the desired Target Sum.
private Stack<Integer> stack = new Stack<>();

// Store the summation of current elements held in stack.
private int sumInStack = 0;

/* A List Interface of Integer[] array to hold all the
combinations of array elements which sum to target. */
private List<Integer[]> combinationsList = new ArrayList<>();


public static void main(String[] args) {
// Demo started this way to avoid the need for statics.
new SumTargetLimit_Demo().startDemo(args);
}

private void startDemo(String[] args) {
// The int array to work against.
int[] intData = {2, 7, 11, 15};

/* See which array elements can acquire the desired
Target Sum with the maximum number of array elements
specified in the numbersLimit member variable. */
getSummations(intData, 0, intData.length);

// Display the found results to Console window...
if (combinationsList.isEmpty()) {
System.err.println("No integer elements within the supplied Array will");
System.err.println("provide a Taget Sum of " + targetSum + " with a maximum number");
System.err.println("limit of " + numbersLimit + ".");
}
else {
for (Integer[] intArray : combinationsList) {
System.out.println(Arrays.toString(intArray).replaceAll("[\\[\\]]", ""));
}
}
}

// Note: This method is recursive...
public void getSummations(int[] data, int startIndex, int endIndex) {
/* Check to see if the sum of array elements stored in the
Stack is equal to the desired Target Sum. If it is then
convert the array elements in the Stack to an Integer[]
Array and add it to the conmbinationsList List. */
if (sumInStack == targetSum) {
if (stack.size() <= numbersLimit) {
combinationsList.add(stack.toArray(new Integer[stack.size()]));
}
}

for (int currIndex = startIndex; currIndex < endIndex; currIndex++) {
if (sumInStack + data[currIndex] <= targetSum) {
stack.push(data[currIndex]);
sumInStack += data[currIndex];

// Make the currentIndex +1, and then use recursion to carry on.
getSummations(data, currIndex + 1, endIndex);
sumInStack -= stack.pop();
}
}
}

}

Try a much larger int[] array and play with the Target Sum and Number Limit to see how things work.

How do I find the sum of integers stored in a string array along with a string in java? I need the 0 in the output to be the sum of the integers

If java 8 is fine, then you could use a more up-to-date approach:

        final Path path = Paths.get("path/to/your/file");
final List<String> lines = Files.readAllLines(path);

int sum = 0;

try {
sum = lines.stream()
.map(line -> line.split(","))
.flatMap(Arrays::stream)
.mapToInt(Integer::parseInt)
.sum();
} catch (Exception ex) {
// do something with exception
}

lines.forEach(System.out::println);
System.out.println(sum);

If the file is large, then play with Files.lines(path) method.

Calculating the sum for each array column

I would create a 1D integer array and use that to store the running sum for each column:

int[][] data = {{1,2,3,4},
{1,2,3,4},
{1,2,3,4}};
int[] colSums = new int[data[0].length];

for (int r=0; r < data.length; ++r) {
for (int c=0; c < data[r].length; ++c) {
colSums[c] += data[r][c];
}
}

System.out.println(Arrays.toString(colSums)); // [3, 6, 9, 12]


Related Topics



Leave a reply



Submit