Logo

Programming-Idioms

  • C++
  • Java
int i = 1, n = x.length, s = x[0];
while (i < n) s = s + x[i++];
int s = 0;
for (int i : x) {
  s += i;
}
import static java.util.stream.IntStream.of;
int s = of(x).sum();
import static java.lang.String.valueOf;
import java.math.BigInteger;
BigInteger s = new BigInteger(valueOf(x[0]));
for (int i = 1, n = x.length; i < n; ++i)
    s = s.add(new BigInteger(valueOf(x[i])));
import static java.util.Arrays.stream;
import java.math.BigInteger;
BigInteger s = stream(x)
    .mapToObj(String::valueOf)
    .map(BigInteger::new)
    .reduce(BigInteger::add)
    .get();
#include <ranges>
auto s = std::ranges::fold_left(x, 0, std::plus<int>{});
#include <functional>
#include <numeric>
int s = std::accumulate(x.begin(), x.end(), 0, std::plus<int>());

std::plus<int>() parameter optional (defaults to this if not provided)
for E of x loop
   S := S + E;
end loop;

x is an array.
S is initialized to be 0.

New implementation...
< >
deleplace