How to Find the Sum of an Array of Numbers

How to find the sum of an array of numbers

Recommended (reduce with default value)

Array.prototype.reduce can be used to iterate through the array, adding the current element value to the sum of the previous element values.

console.log(

[1, 2, 3, 4].reduce((a, b) => a + b, 0)

)

console.log(

[].reduce((a, b) => a + b, 0)

)

Simple Array Sum using javascript (single integer)

There are two problems in your code. You need to change

sum += (ar); to sum += (ar[i]);

so as to sum the element at that index and not the ar itself. Also return should be outside the loop and should actually be the return of the function. Otherwise, for..loop will just return after the first execution.

function simpleArraySum(ar) {
var sum = 0;
for (var i = 0; i < ar.length; i++) {
if(typeof ar[i] == `number`) sum += ar[i];
}
return sum;
}

console.log(simpleArraySum([1, 2, 3, 4]))

finding the sum of numbers in an array

You should reset the sum variable before you run the loop, otherwise it will still contain the previous sum.

void draw() {
sum = 0;
for (int i =0; i<f.length; i++) {
sum +=f[i];
}
println(sum);

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 to compute the sum and average of elements in an array?

var sum = 0;
for( var i = 0; i < elmt.length; i++ ){
sum += parseInt( elmt[i], 10 ); //don't forget to add the base
}

var avg = sum/elmt.length;

document.write( "The sum of all the elements is: " + sum + " The average is: " + avg );

Just iterate through the array, since your values are strings, they have to be converted to an integer first. And average is just the sum of values divided by the number of values.

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 negative and positive numbers in array to get a result

The problem here is that your array is actually an array of strings instead of numbers. So in reality, you need to convert the array to an array of numbers and then you can sum the values.

const arr = ['-8', '-3', '1', '-4', '0'];
const sum = arr.reduce((acc, value) => acc + Number(value), 0); // -14

How to find the sum of an array of numbers

Recommended (reduce with default value)

Array.prototype.reduce can be used to iterate through the array, adding the current element value to the sum of the previous element values.

console.log(

[1, 2, 3, 4].reduce((a, b) => a + b, 0)

)

console.log(

[].reduce((a, b) => a + b, 0)

)

Increase or decrease numbers of an array so the sum of them always remains 100

You could check if there is a value for decrementing and add all changes to the sum for incrementing a value.

const
change = (array, index, direction) => {
if (direction === 1) {
const step = 1 / array.length;
for (let i = 0; i < array.length; i++) {
if (i === index || array[i] === 0) continue;
const s = Math.min(step, array[i]);
array[i] -= s;
array[index] += s;
}
} else {
const step = Math.min(1 / array.length, array[index] / (array.length - 1));
for (let i = 0; i < array.length; i++) {
if (i === index) continue;
array[i] += step;
array[index] -= step;
}
}
return array;
},
values = [96.8, 0.2, 1, 1, 1],
display = values => values.forEach((v, i) => document.getElementById('value' + i).innerHTML = v.toFixed(2)),
addEvent = (type, index) => event => {
change(values, index, type === 'up' ? 1 : -1);
display(values);
};


[...document.getElementsByTagName('button')].forEach(element => {
const [type, index] = element.id.match(/\d+|\D+/g);
element.addEventListener('click', addEvent(type, +index));
});

display(values);
.as-console-wrapper { max-height: 100% !important; top: 0; }
td { text-align: center; width: 20%; }
<table>
<tr>
<td><button id="up0">^</button></td>
<td><button id="up1">^</button></td>
<td><button id="up2">^</button></td>
<td><button id="up3">^</button></td>
<td><button id="up4">^</button></td>
</tr>
<tr>
<td id="value0"></td>
<td id="value1"></td>
<td id="value2"></td>
<td id="value3"></td>
<td id="value4"></td>
</tr>
<tr>
<td><button id="down0">v</button></td>
<td><button id="down1">v</button></td>
<td><button id="down2">v</button></td>
<td><button id="down3">v</button></td>
<td><button id="down4">v</button></td>
</tr>
</table>


Related Topics



Leave a reply



Submit