Sum of elements#7829

Sum of elements (Editorial)

Compute the sum of the numbers using a loop.

Algorithm implementation

Declare an array.

double m[100];

Read the input data.

scanf("%d",&n);
for (i = 0; i < n; i++)
  scanf("%lf",&m[i]);

In the variable , compute the sum of all numbers in the array .

s = 0;
for (i = 0; i < n; i++)
  s = s + m[i];

Print the resulting sum.

printf("%.1lf\n",s);

Algorithm implementation — loop

Read the input value of .

scanf("%d",&n);

In the variable , compute the sum of numbers.

s = 0;
for (i = 0; i < n; i++)
{
  scanf("%lf",&x);
  s = s + x;
}

Print the answer.

printf("%.1lf\n",s);

Algorithm implementation — vector

Declare a vector to store the input array.

vector<double> m;

Read the input data.

scanf("%d", &n);
m.resize(n);
for (i = 0; i < n; i++)
  scanf("%lf", &m[i]);

In the variable , compute the sum of all numbers in the array .

s = 0;
for (i = 0; i < n; i++)
  s = s + m[i];

Print the answer.

printf("%.1lf\n", s);

Algorithm implementation — accumulate

Declare a vector to store the input array.

vector<double> v;

Read the input data.

scanf("%d", &n);
v.resize(n);
for (i = 0; i < n; i++)
  scanf("%lf", &v[i]);

Compute the sum of the numbers in the array using the accumulate function.

s = accumulate(v.begin(), v.end(), 0.0);

Print the answer.

printf("%.1lf\n", s);

Java implementation

public class Main
{
  public static void main(String[] args)
  {
    Scanner con = new Scanner(System.in);
    con.useLocale(Locale.US);
    int n = con.nextInt();
    double sum = 0;
    for (int i = 0; i < n; i++) 
    {
      double val = con.nextDouble();
      sum += val;
    }
    System.out.printf("%.1f",sum);
    con.close();
  }
}

Python implementation

Read the input data.

n = int(input())
m = list(map(float,input().split()))

Compute and print the answer.

print(sum(m))