Write C program to find maximum and minimum elements in array using recursion


Introduction

I have used Code::blocks 12 compiler for debugging purpose. But you can use any C programming language compiler as per your availability.


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

Write C program to find maximum and minimum elements in array using recursion


  1. #include <stdio.h>
  2. #define MAX_SIZE 100
  3.  
  4. // Function declarations
  5. int Findmaxnumber(int array[], int index, int len);
  6. int Findminnumber(int array[], int index, int len);
  7.  
  8.  
  9. int main()
  10. {
  11. int array[MAX_SIZE], Num, max, min;
  12. int i;
  13.  
  14. // Inputting size and elements of array
  15. printf("Enter size of the array: ");
  16. scanf("%d", &Num);
  17. printf("Enter %d elements in array: ", Num);
  18. for(i=0; i<Num; i++)
  19. {
  20. scanf("%d", &array[i]);
  21. }
  22.  
  23. max = Findmaxnumber(array, 0, Num);
  24. min = Findminnumber(array, 0, Num);
  25.  
  26. printf("Minimum element in array: %d\n", min);
  27. printf("Maximum element in array: %d\n", max);
  28.  
  29. return 0;
  30. }
  31.  
  32.  
  33. //Recursive function to find maximum element in the given array.
  34. int Findmaxnumber(int array[], int index, int len)
  35. {
  36. int max;
  37. if(index >= len-2)
  38. {
  39. if(array[index] > array[index + 1])
  40. return array[index];
  41. else
  42. return array[index + 1];
  43. }
  44.  
  45. max = Findmaxnumber(array, index + 1, len);
  46.  
  47. if(array[index] > max)
  48. return array[index];
  49. else
  50. return max;
  51. }
  52.  
  53. //Recursive function to find minimum element in the array
  54. int Findminnumber(int array[], int index, int len)
  55. {
  56. int min;
  57.  
  58. if(index >= len-2)
  59. {
  60. if(array[index] < array[index + 1])
  61. return array[index];
  62. else
  63. return array[index + 1];
  64. }
  65.  
  66. min = Findminnumber(array, index + 1, len);
  67.  
  68. if(array[index] < min)
  69. return array[index];
  70. else
  71. return min;
  72. }
  73.  

Result

C language

     





Related Topics




Popular Posts