how to add numbers in an array code example
Example 1: adding numbers in an array javascript
console.log(
[].reduce((a, b) => a + b)
)
Example 2: how to add up all numbers in an array
var numbers = [10, 20, 30, 40]
var sum = 0;
for (var i = 0; i < numbers.length; i++) { sum += numbers[i]}
Example 3: how to add up all numbers in an array
const numbers = [10, 20, 30, 40]
add = (a, b) => a + b
const sum = numbers.reduce(add)
Example 4: add each element in an array java
import java.util.Arrays;
import java.util.Scanner;
public class SumOfElementsOfAnArray {
public static void main(String args[]){
System.out.println("Enter the required size of the array :: ");
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int myArray[] = new int [size];
int sum = 0;
System.out.println("Enter the elements of the array one by one ");
for(int i=0; i<size; i++){
myArray[i] = s.nextInt();
sum = sum + myArray[i];
}
System.out.println("Elements of the array are: "+Arrays.toString(myArray));
System.out.println("Sum of the elements of the array ::"+sum);
}
}
Example 5: sum of arrays
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int i, n, sum=0;
printf("Enter size of the array: ");
scanf("%d", &n);
printf("Enter %d elements in the array: ", n);
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
for(i=0; i<n; i++)
{
sum = sum + arr[i];
}
printf("Sum of all elements of array = %d", sum);
return 0;
}