Write C++ program to find sum of natural numbers in given range 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.  
  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. cout<<"Enter lower limit: ";
  13. cin>>start;
  14. cout<<"Enter upper limit: ";
  15. cin>>end;
  16.  
  17. sum = sumofnnumbers(start, end);
  18.  
  19. cout<<"Sum of natural numbers from "<<start <<" to "<<end << ": " <<sum;
  20.  
  21. return 0;
  22. }
  23.  
  24. //Recursively find the sum of natural number
  25.  
  26. int sumofnnumbers(int start, int end)
  27. {
  28. if(start == end)
  29. return start;
  30. else
  31. return start + sumofnnumbers(start + 1, end);
  32. }

Result

C++ language techstudy.org

     





Related Topics




Popular Posts