forked from Astha369/CPP_Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursive.cpp
More file actions
32 lines (24 loc) · 732 Bytes
/
recursive.cpp
File metadata and controls
32 lines (24 loc) · 732 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Problem Statement:
// Write a C++ program to find the sum of natural numbers up to a given positive integer using recursion.
// Solution:
#include <iostream>
// Function to calculate the sum of natural numbers up to n using recursion
int sumOfNaturalNumbers(int n) {
if (n <= 0) {
return 0;
} else {
return n + sumOfNaturalNumbers(n - 1);
}
}
int main() {
int num;
std::cout << "Enter a positive integer: ";
std::cin >> num;
if (num < 0) {
std::cout << "Please enter a positive integer." << std::endl;
return 1;
}
int sum = sumOfNaturalNumbers(num);
std::cout << "Sum of natural numbers up to " << num << " is " << sum << std::endl;
return 0;
}