Not understanding output

I am taking a C++ Programming class and my final is on Friday. This is one of the questions on the final exam study guide. The question assumes that the user inputs 11. I typed the code into Dev C++, entered 11 and the output was "C++ is fun". I understand that 11 is greater than 0, that's why "C++" is outputted but why is "is fun" added to the output and where did the word "soccer" go? Does it have to do with the else statements not enclosed within curly braces?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

int main()
{
int number;
cin >> number;
if (number > 0)
cout << "C++";

else 

cout << "Soccer ";
cout << "is ";
cout << "fun " << endl;

return 0;
}
Last edited on
Does it have to do with the else statements not enclosed within curly braces?

Yes. Line 15 and 16 is not part of the if-else and will always be executed.
"soccer" was skipped because the else applies only to the next statement (line 14, no curly braces). Don't let the spacing fool you. Lines 15 and 16 are unconditional because they are NOT within scope of the else.
Last edited on
Topic archived. No new replies allowed.