Puzzle DB11


Add up all the integers in an array of integers

[E-6] Write a function that computes the sum of all the elements in an array of integers. A related problem is to compute the average of the elements in an array, but that is just a small change to this function. Here is a framework:

/* Puzzle D11 -- add up all the integers in an array of integers */

long addArray( int size, int arr[] )
{
.....
}

void printArray( int size, int arr[] )
{
  const int N = 10;
  int j;
  
  for ( j=0; j<size; j++ )
  {
    if ( j%N == N-1 )
      printf("%4d\n", arr[j] );
    else
      printf("%4d ", arr[j] );    
  }
}

#define SIZE 10
int main()
{
  int x[ SIZE ] = { -1, 1, -2, 2, -3, 3, -4, 4, -5, 5 };
  
  printArray( x, SIZE );
  printf("\n");
  printf("sum = %ld\n", addArray( SIZE, x ) );
  
  return 0;
}


Answer         Next Page         Previous Page Home