SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
C++ Basics
Exercise:
Self-test Exercises
Question:27 | ISBN:9780321531346 | Edition: 7

Question

What is the output of the following cout statements embedded in these if-else statements? You are to assume that these are embedded in a complete correct program. Explain your answer.

a. if(0)

cout << "0 is true";

else

cout << "0 is false";

cout << endl;

b. if(1)

cout << "1 is true";

else

cout << "1 is false";

cout << endl;

c. if(-1)

cout << "-1 is true";

else

cout << "-1 is false";

cout << endl;

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

a)

The output of the given code snippet for the statement if (0) will be:

0 is false

Explanation:

Since the condition if (0) evaluates to false (0 is considered false in C++), the code will execute the else block.

Hence, the output will be "0 is false".

b)

The output of the code snippet for the statement if (1) will be:

1 is true

Explanation:

In C++, any non-zero value is considered true. Since the condition if (1) evaluates to true, the code will execute the if block.

Therefore, the output will be "1 is true".

c)

The output of the code snippet for the statement if (-1) will be:

-1 is true

Explanation:

Similar to the previous case, any non-zero value is considered true in C++. Since the condition if (-1) evaluates to true, the code will execute the if block.

Hence, the output will be "-1 is true".

In all cases, the cout << endl; statement adds a new line after printing the message, resulting in each message appearing on a separate line in the output.

0 0

Discussions

Post the discussion to improve the above solution.