Write C program to find sum of natural numbers in given range 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 natural numbers in given range using recursion


  1. #include <stdio.h>
  2.  
  3.  
  4. // Function declaration
  5. int sumofnnumbers(int start, int end);
  6.  
  7. int main()
  8. {
  9. int start, end, sum;
  10.  
  11. // Inputting lower and upper limit from user
  12. printf("Enter lower limit: ");
  13. scanf("%d", &start);
  14. printf("Enter upper limit: ");
  15. scanf("%d", &end);
  16.  
  17. sum = sumofnnumbers(start, end);
  18.  
  19. printf("Sum of natural numbers from %d to %d : %d", start, end, sum);
  20.  
  21. return 0;
  22. }
  23.  
  24.  
  25. //Recursively find the sum of natural number
  26.  
  27. int sumofnnumbers(int start, int end)
  28. {
  29. if(start == end)
  30. return start;
  31. else
  32. return start + sumofnnumbers(start + 1, end);
  33. }
  34.  

Result

C language

     





Related Topics




Popular Posts