Answer DB11

#include <stdio.h>
#include <stdlib.h>

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

long addArray( int size, int arr[] )
{
  int j;
  long sum = 0;
  
  for ( j=0; j<size; j++ )
    sum += arr[j] ;
    
  return sum;
}

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( SIZE, x );
  printf("\n");
  printf("sum = %ld\n", addArray( SIZE, x ) );
  
  return 0;
}

Comments: The function returns a long int. If the array is too large, even a long might not be big enough. Depending on the situation, the sum and return value might be made double precision floating point.

Of course, floating point computations are always inexact. In a real-world program (perhaps one dealing with financial data), inexact calculations might not be acceptable.

The format code %ld is used to match the long return type of the function.

Even such a seemingly easy puzzle as this has things to think about.



Back to Puzzle Home