Calculating the Sum of an Array in C

C provides easy access to array structures. Arrays are, in fact, one of the most important ways to access low level data in the C language.

To demonstrate the simple way in which you can convert between pointers and array values in C, we can study a simple program to calculate the sum of n numbers, where the numbers are provided as the content of an array of doubles.

First, we declare the array and its size:

#define ARRAY_SIZE 100
double number_array[ARRAY_SIZE];

Then, we create a main function that will read the values as they are provided by the user:

int main() {
  int i;
  for (i=0; i<ARRAY_SIZE; ++i) {
     scanf("%lf", &number_array[i]);
  }
  double sum = array_sum();
  printf("sum is %lf\n", sum);
}

What this code is doing is first, read the numbers from standard input, using the scanf function. If you need additional information about scanf, please check the appropriate man function.

Then the code is calling the array_sum function, which we will explain next. Finally, it prints the sum of the values as calculated above.

The array_sum function can be written as follows:

double array_sum() {
  double result = 0;
  for (i=0; i<ARRAY_SIZE; ++i) {
     result += number_array[i];
  }
  return result;
}
Tags: array, sum
Article created on 2012-05-05 06:59:15

Post a comment