2

I want to compute the sum of the following series:

5 + 8 + 11 + .... + 50

I wish to use a for loop to print the above series and the sum of the series. I have written the following code:

#include <iostream>
using namespace std;

int main()
{
    int i, sum = 0, n = 50;
    cout << "\n\n THE SERIES IS UNDER : \n\n\n";
    i = 2;
    while(i <= n)
    {
        sum = sum + i;
        if (i == 2)
            cout << i;
        else
            cout << " + "<< i;
        i = i + 3;
    }
    cout << "\n\n\n THE SUMMATION IS "<< sum;
    return 0;
}

2 Answers2

4
cout<<"\n\n\n THE SUMMATION IS ",sum;

->

cout << "\n\n\n THE SUMMATION IS " << sum;

and

cout<<" + ",i;

->

cout << " + " << i;

The comma (,) operator does not work here like the stream (<<) operator.

user123
  • 8,970
  • 2
  • 31
  • 52
4
#include<iostream>
using namespace std;

int main()
{
    cout << "\n\n THE SERIES IS UNDER : \n\n\n";

    int sum = 0;
    for (int i = 5; i < 50; i += 3) {
        cout << i << '+';
        sum += i;
    }
    cout << 50 << endl;
    sum += 50;

    cout << "\n\n\n THE SUMMATION IS " << sum << endl;
    return 0;
}

Changes in this version:

  1. Include iostream instead of iostream.h; this is more portable between compilers
  2. Using a for loop here is more concise and clear.
  3. The test if (i == 2) cout << i; is a waste of time because it's true for only one iteration. Instead you can handle the first item or the last item as a special case outside of the for loop.
  4. Use sum += i instead of sum = sum + i, since the former is more clear and efficient. Most programmers will choose the former one by default.
  5. Generally you want to use cout << endl in C++. There is a difference between '\n' and endl, unless you have a reason not to do so. See the post: C++: "std::endl" vs "\n"
Community
  • 1
  • 1
gongzhitaao
  • 6,566
  • 3
  • 36
  • 44
  • You've changed a few different things at once here; this answer could be improved by adding a little commentary about what you changed and why, so the original requester can learn from each of these changes. – Martin Atkins Mar 23 '13 at 15:52
  • Sure, that's fine. I didn't intentionally remove it, our edits just collided. Sorry. To avoid the same happening again, I'll leave further edits up to you. – Martin Atkins Mar 23 '13 at 16:11
  • @MartinAtkins Thanks for your wording :) – gongzhitaao Mar 23 '13 at 16:14