-3

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;
}
Press Awesome
  • 37
  • 2
  • 10
  • Possible duplicate of https://stackoverflow.com/questions/36137997/convert-vectorunsigned-char-1-2-3-into-string-1-2-3-as-digits/36138229#36138229 – Galik Dec 05 '16 at 00:49
  • Also maybe of use https://stackoverflow.com/questions/35858896/c-compare-and-replace-last-character-of-stringstream/35859132#35859132 – Galik Dec 05 '16 at 00:49
  • 1
    If your going to down vote the question, comments as to why would be nice. I have been looking for a solution to this for an hour now. As far as being unclear...I believe I was perfectly clear about the need here. As far as useful goes, this could be absolutely useful to someone. – Press Awesome Dec 05 '16 at 00:51

3 Answers3

1
bool plus = false;
for (int i = 1; i <= n; i++) {
    cout << (plus ? " + " : "") << i;
    plus = true;
}
Paul J. Lucas
  • 6,895
  • 6
  • 44
  • 88
1
for (int i = 1; i <= n; i++)
{
    cout << i << " + ";
}

Should be rewritten as

for (int i = 1; i <= n; i++)
{
    cout << i;
    if(i != n) cout << " + ";
}
Xirema
  • 19,889
  • 4
  • 32
  • 68
  • Thank You your answer was perfect. I really appreciate it. I have been looking at this for a while and could not figure it out. LOL. Again thanks. – Press Awesome Dec 05 '16 at 00:44
1

Just need 2 small edits to your code:

for (int i = 1; i <= n; i++)
{
    cout << i << " + ";
}

this becomes:

for (int i = 1; i < n; i++)
{
    cout << i << " + ";
}
cout << 10;
Ben
  • 138
  • 2
  • 9