7

I copied this code from C++ Primer as an example for while loops, and it doesn't output anything. I'm using g++.

#include <iostream>

int main()
{
    int sum = 0, val = 1;
    // keep executing the while as long val is less than or equal to 10
    while (val <= 10) {
        sum += val;     // assigns sum+ val to sum\
        ++val;          // add 1 to val
    }
    std::cout << "Sum of 1 to 10 inclusive is "
              << sum << std::endl;
    return 0;
}
0

3 Answers 3

11
sum += val;     // assigns sum+ val to sum\

Get rid of the backslash at the end of the line. That's a line continuation character. It causes the next line to be concatenated to this line; in other words, ++val becomes part of the "assigns sum+ val to sum" comment.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a perfect example of why minimal reproducible examples are important.
4
    sum += val;     // assigns sum+ val to sum\ <-- typo
    ++val;          // add 1 to val

You got a typo at that sum += val; line. The "\" at the end make the following line a comment, thus making the while an infinite loop as val was never increased. Remove "\", then it would work.

Comments

1

It's a simple mistake, remove the \ after the comment "// assigns sum+ val to sum".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.