Sum of N Even number using Recursion

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

Note : This Problem is part of Recursion series. Make sure to solve previous questions of series for better understanding.

Example :

Input : 10
Output : 30

Input : 5
Output : 6
 
int prime(int n)
{  
  //Base Check
  if (n==0) return 0;

  //Recursive call
  else return n + prime(n-2);  
}

int main()
{
  int n;
  cin >> n;

  //For odd number decrease by 1
  if(n%2!=0) n--;

  cout << prime(n);
  
  return 0;
}

No comments:

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

Powered by Blogger.