Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

Find the minimum value in an array using C programming

Write a recursive function recursiveMinimum that takes an integer array and the array size as arguments and returns the smallest element of the array. The function should stop processing and return when it receives an array of one element.

Answer:


#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10
#define MAXRANGE 1000

// function prototype
int recursiveMinimum( int array[], int low, int high );

int main( void )
{ 
   int array[ SIZE ]; // array to be searched
   int loop; // loop counter
   int smallest; // smallest element

   srand( time( NULL ) );

   // initialize elements of array to random numbers
   for ( loop = 0; loop < SIZE; ++loop ) {
      array[ loop ] = 1 + rand() % MAXRANGE;
   } // end for

   printf( "Array members are:\n" );

   // display array
   for ( loop = 0; loop < SIZE; ++loop ) {
      printf( " %d ", array[ loop ] );
   } // end for

   // find and display smallest array element
   puts( "" );
   smallest = recursiveMinimum( array, 0, SIZE - 1 );
   printf( "\nSmallest element is: %d\n", smallest );
} 

// function to recursively find minimum array element
int recursiveMinimum( int array[], int low, int high )
{ 
   int min; // int to store current minimum value

   // if the array has only one element,
   // the value of that element is the array’s smallest value
   if ( low == high )
      return array[ high ];
   else {
      min = recursiveMinimum( array, low + 1, high );
      return array[ low ] < min ? array[ low ] : min;
   } 
} 

About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!