Decision Making help Exercise

I'm doing the exercise on my "How to program C++" book and the question said "If the variable number is not wqual to 7, print "The variable number is not equal to 7". Here what I put for my answer:

if (number != 7) cout << number << " The variable is not equal to 7 " << 7 << endl;

but when I look at the answer its......: if ( number != 7 )std::cout << "The variable number is not equal to 7\n";

My question is, isn't those 2 the same? If not, why? :( Sorry for my bad english/grammer. lol
Last edited on
It's not really the same. You know why?

Code:
if(number != 7) std::cout << number << " The variable is not equal to 7 " << 7 << endl;Output (if input is, like, 8):
8 The variable is not equal to 7 7
As you can see, you are writing the variable at the beginning, and also you are writing 7 twice. The second way is the cleaner one, as it prints no variable and prints '7' once.

You can solve it in two ways:
1
2
if(number != 7) std::cout << "The variable number is not equal to 7\n";
// Remember: \n into a string is like endl. 
(This is the answer)

Or also:
if(number != 7) std::cout << "Your Variable, " << number << ", Is not equal to 7!\n";
(This is how I would have written it)

Let's show them all:

Your Method:
8 The variable is not equal to 7 7
The Answer:
The variable number is not equal to 7
My Answer:
Your Variable, 8, Is not equal to 7!
Last edited on
Topic archived. No new replies allowed.