Sum of Array Elements
Add up all the elements of an array.
Sample input
[10, 20, 30, 40]
Sample output
100
Solution
arr = [10, 20, 30, 40]
print(sum(arr))
const arr = [10, 20, 30, 40];
console.log(arr.reduce((a, b) => a + b, 0));
public class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40};
int total = 0;
for (int x : arr) total += x;
System.out.println(total);
}
}
fun main() {
val arr = intArrayOf(10, 20, 30, 40)
println(arr.sum())
}
let arr = [10, 20, 30, 40]
print(arr.reduce(0, +))
void main() {
List<int> arr = [10, 20, 30, 40];
int total = arr.reduce((a, b) => a + b);
print(total);
}
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40};
int n = 4, total = 0;
for (int i = 0; i < n; i++) total += arr[i];
cout << total << endl;
return 0;
}
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40};
int n = 4, total = 0;
for (int i = 0; i < n; i++) total += arr[i];
printf("%d\n", total);
return 0;
}