Sum of N Natural number

Given number N, task is to find the sum 1 + 2 + 3 + ... + n. Using Recursion.

Example :

Input :
Output : 15
 
Approach : Till the value becomes 1 recursively add the value.

int sum(int n)
{
  int s=0;
  //Base Case
  if (n==1) return n;
  
  //Recursive Call
  else return n + sum(n-1);
}

int main()
{
  int n;
  cin >> n;
  cout << sum(n);
  
  return 0;
} 


No comments:

If you have any doubt or suggestion let me know in comment section.

Powered by Blogger.