Write C++ program to find sum of array elements using recursion


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.  
  4. #define MAX_SIZE 100
  5.  
  6. // Function declaration
  7. int sum(int arr[], int start, int len);
  8.  
  9.  
  10. int main()
  11. {
  12. int arr[MAX_SIZE];
  13. int num, i, sumofarray;
  14.  
  15.  
  16. // Inputtin size and elements in array
  17. cout<<"Enter size of the array: ";
  18. cin>>num;
  19. cout<<"Enter elements in the array: ";
  20. for(i=0; i<num; i++)
  21. {
  22. cin>>arr[i];
  23. }
  24.  
  25.  
  26. sumofarray = sum(arr, 0, num);
  27. cout<<"Sum of array elements: "<<sumofarray;
  28.  
  29. return 0;
  30. }
  31.  
  32. // Recursively finding the sum of elements in an array.
  33. int sum(int arr[], int start, int len)
  34. {
  35. // Recursion base condition
  36. if(start >= len)
  37. return 0;
  38.  
  39. return (arr[start] + sum(arr, start + 1, len));
  40. }

Result

C++ language techstudy.org

     





Related Topics




Popular Posts