-4
#include <iostream>
using namespace std;

int main() {
    int sum(1), count(1);
    while (count <= 6) {
        sum += (2*count + 1);
        count++;
    } 
    cout << "sum = " << sum << endl; 

    return 0;
}

I have this C++ code that is suppose to print the sum of the six consecutive odd numbers, starting  from the number 1. I need to fix it by using a variable tracing cout statement. I want the statement to show what the value of the variable and sum is at each iteration is. Please help.

David Rawson
  • 20,912
  • 7
  • 88
  • 124
Adam22
  • 1
  • 2
  • Plus one for the nicely written question. How about you put a `cout` statement within the `while` loop? – Bathsheba May 04 '17 at 06:58
  • 2
    Just add `cout << "sum = " << sum << " count = " << count << endl;` on the first line in the while loop. In this case it is important to use `std::endl` rather than `'\n'`, since the former will add a line break and also flush the stream. – Jonas May 04 '17 at 06:59
  • 1
    @Jonas I don't think `std::endl` is really important here. The entire program will likely run faster than the update frequency of your screen ... – chtz May 04 '17 at 07:33
  • @chtz I suppose that depends on the range, in this case it is short, so partly yes. On the other hand it is always appropriate to use `std::endl` when printing debug information, to avoid buffering. – Jonas May 04 '17 at 07:37
  • @Jonas still, I would only flush, if I'd be worried that the execution between consecutive `cout` might crash (and thus lose information). But that is maybe more topic of e.g. http://stackoverflow.com/questions/213907/c-stdendl-vs-n – chtz May 04 '17 at 07:51

1 Answers1

2

Just put a cout inside your loop.

int main() {
    int sum(1), count(1);
    while (count <= 6) {
        sum += (2*count + 1);
        count++;
        cout << "current sum = " << sum << endl;
    } 
    cout << "sum = " << sum << endl; 

    return 0;
}

EDIT This is the form, at least, of how you'd go about doing it. This seems like a homework problem, so I'll let you handle the output formatting, as well as incorporating the variables you want.

Arya McCarthy
  • 8,554
  • 4
  • 34
  • 56
  • 2
    I'm not downvoter. Why would you print after `count++`? – Jonas May 04 '17 at 07:03
  • I was. (i) the `cout` is in the wrong place in the loop, (ii) doesn't contain all the variables the OP wants to see, (iii) is a "give a fish" rather than "teach how to fish" answer, (iv) is the use of `endl` justified? – Bathsheba May 04 '17 at 07:06
  • (i) The asker was unclear about whether "at each iteration" meant before or after modification. (iii) Arguably, by not containing all the variables, it gives the OP an opportunity to fish. – Arya McCarthy May 04 '17 at 07:07
  • @Bathsheba I'm curious about your thoughts on the matter. – Arya McCarthy May 04 '17 at 07:11