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


I have used CodeBlocks 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

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


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

Result

C++ language techstudy.org

     





Related Topics




Popular Posts