Sum of first n natural numbers using recursion.

PHOTO EMBED

Tue Feb 11 2025 05:26:37 GMT+0000 (Coordinated Universal Time)

Saved by @Rohan@99

#include <iostream>
using namespace std;

int SumOfNNaturalNumbers(int n)
{
  if(n == 1)
    return 1;
    
  return (n + SumOfNNaturalNumbers(n-1));
}

int main() 
{
  int n;
  cin >> n;
  
  cout << "Sum of first " << n << " natural numbers: " << SumOfNNaturalNumbers(n) << endl;
  return 0;
}
content_copyCOPY