Write C program to find sum of array elements 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 sum of array elements using recursion


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

Result

C language

     





Related Topics




Popular Posts