Advertisement
defineSN

min of array using recursion

Feb 3rd, 2013
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.34 KB | None | 0 0
  1. /*minimum of an array using recursion*/
  2.  
  3. #include<stdio.h>
  4. #include<stdlib.h>
  5.  
  6. int findMin(int* arr,int min,int size);
  7. int* populateArray(int size); // return type pointer
  8. void printArray(int* arr,int size);
  9. int main(){
  10.    
  11.     int i=0,size=0,min=0;
  12.     int* arr;
  13.    
  14.     printf("enter size of array: ");
  15.     scanf("%d",&size);
  16.    
  17.     arr=populateArray(size);
  18.    
  19.     printf("array is: ");
  20.     printArray(arr,size);
  21.    
  22.     min=*(arr+0);
  23.    
  24.     min=findMin(arr,min,size);
  25.     printf("\n\nthe min value in the arr is: %d\n",min);
  26.    
  27.     //getch(); // add this line if you are not running from command line
  28.     return 0;  
  29.  
  30. }
  31.  
  32. int* populateArray(int size){
  33.     int i=0;
  34.     int* arr;
  35.    
  36.     arr=(int*)malloc(sizeof(int)*size);
  37.    
  38.     srand(time(NULL)); //creates seed for rand() by taking system exec time
  39.     for(i=0;i<size;i++){
  40.         *(arr+i)=(rand()%1000); // populates array with integers 0-999 
  41.     }  
  42.     return arr;
  43. }
  44.  
  45. void printArray(int* arr,int size){
  46.    
  47.     int i;
  48.     for(i=0;i<size;i++)
  49.     printf("%d ",*(arr+i));
  50.     puts("\n");
  51. }
  52.  
  53.  
  54. int findMin(int *arr, int min, int size)
  55. {
  56.     if (size == 0) {
  57.         printf("in findMin() : passed values >> min:%5d  size:%3d\n", min, size);
  58.         return min;
  59.     }
  60.     printf("in findMin() : passed values >> array:%5d  min:%d  size:%3d\n", *(arr), min, size);
  61.     if (min > *arr)
  62.         min = *arr;
  63.     return findMin(arr + 1, min, size - 1);
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement