C11 Answer


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

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

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

void printArray( int arr[], int size )
{
  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 argc, char *argv[])
{
  int x[ SIZE ] = { -1, 1, -2, 2, -3, 3, -4, 4, -5, 5 };
  
  printArray( x, SIZE );
  printf("\n");
  printf("sum = %ld\n", addArray( x, SIZE ) );
  
  system("pause");	
  return 0;
}

Comments: The function returns a long int. If the array is too large, even a long might not be big enough. In that case, the sum and an return value should be 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.