Program to calculate the sum of numbers from 1 to n using recursion in C++.
Solution
#include <iostream> using namespace std; int sum(int n) { if (n != 0) return n + sum(n - 1); else return n; } int main() { int n,ans; cout<<"Enter a Number "; cin>>n; ans=sum(n); cout<<"Sum of first n natural number is :- "<<ans; return 0; }
Output :
Enter a Number 10 Sum of first n natural number is :- 55