#include <iostream>
using namespace std;
int sum(int n) {
if (n == 0) {
return 0;
} else {
return n + sum(n - 1);
}
}
int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;
cout << "The sum of natural numbers up to " << n << " is " << sum(n) << endl;
return 0;
}
Enter a positive integer: 20
The sum of natural numbers up to 20 is 210
sum
that takes a positive integer n
as its argument. If n
is 0
, the function returns 0
; otherwise, it returns n
plus the result of calling sum(n - 1)
. main()
, the user is prompted to enter a positive integer, and the sum
function is called with that integer as its argument. The result is then printed out.