This is a C++ question. The program looks like this:
Enter a positive integer: 10
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + = 55
Problem is that it is adding a plus(+) sign to the last number in the list like in the example above. How do I get it to terminate before the last number?
It should look like this below:
Enter a positive integer: 10
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
#include<iostream>
using namespace std;
int add(int n);
int main()
{
int n;
cout << "Enter a positive integer: ";
cin >> n;
for (int i = 1; i <= n; i++)
{
cout << i << " + ";
}
cout << " = " << add(n);
cout << "";
cout << endl;
system("pause");
return 0;
}
// Function to calculate the sum of the numbers using recursion
int add(int n)
{
if (n != 0)
return n + add(n - 1);
return 0;
}