Answer DA3

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

/* Puzzle D03 - fill an array by making each element the same integer val */
void fillArrayConst( int size, int arr[], int val )
{
  int j;
  
  for ( j=0; j<size; j++ )
  {
    arr[j] = val;
  }
}

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] );    
  }
}

const int SIZE = 100;
int main(int argc, char *argv[])
{
  int x[ SIZE ];
  
  fillArrayConst( SIZE, x, 7 );
  printArray( SIZE, x );
    
  printf("\n");
  return 0;
}

A more elaborate testing program follows. It it, the user can specify the array size and the fill value. The array is allocated as a local variable in the function tester(). This means it is created out of main memory on the run-time stack. This works for gcc, but does not work for some older compilers.

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

/* Puzzle D03improved - fill an array by making each element the same integer val */

void fillArrayConst( int size, int arr[], int val )
{
  int j;
  
  for ( j=0; j<size; j++ )
  {
    arr[j] = val;
  }
}

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] );    
  }
}

void tester( int size, int val )
{
  int x[ size ];
  
  fillArrayConst( size, x, val );
  printArray( size, x );
    
  printf("\n");
}

int main(int argc, char *argv[])
{
  int sz, fill;
  printf("Size of the array: ");
  scanf( "%d", &sz );
  printf("Fill value: ");
  scanf( "%d", &fill );
  tester( sz, fill );
  return 0;
}


Back to Puzzle Home