47.7k views
2 votes
What is output by the following C# code segment? int temp; temp = 180; while ( temp != 80 ) { if ( temp > 90 ) { Console.Write( "This porridge is too hot! " ); // cool down temp = temp – ( temp > 150 ? 100 : 20 ); } // end if else { if ( temp < 70 ) { Console.Write( "This porridge is too cold! "); // warm up temp = temp + (temp < 50 ? 30 : 20); } // end if } // end else } // end while if ( temp == 80 ) Console.WriteLine( "This porridge is just right!" );

User Cleveland
by
5.2k points

2 Answers

2 votes

Answer and Explanation:

The output by the following C# code segment is (b): This porridge is too hot! This porridge is just right!

Explanation: first of all in this program declare a temp variable and assign a value 180 after that condition in the while-loop statement and if statement under while-loop will

check first time it will true and console report showing result (This porridge is too hot!) and change the temp value from next line now temp value is set to 80 now first iteration of loop is completed and in next iteration, while loop condition is check now its condition is false so skip the loop and go to if state where check temp = 80 and print console value (This porridge is just right!)

User JLearner
by
5.1k points
3 votes

Answer:

The output of the code is

This porridge is too hot!

This porridge is just right

Explanation:

First, I'll need to arrange the code properly

int temp;

temp = 180;

while ( temp != 80 ) {

if ( temp > 90 ) {

Console.Write( "This porridge is too hot! " ); // cool down

temp = temp – ( temp > 150 ? 100 : 20 ); } // end if

else {

if ( temp < 70 ) {

Console.Write( "This porridge is too cold! "); // warm up

temp = temp + (temp < 50 ? 30 : 20);

} // end if

} // end else

} // end while

if ( temp == 80 )

Console.WriteLine( "This porridge is just right!" );

At line 2, the value of temp is 180

At line 3, an iterative statement is used to test if temp is not Equal to 80.

The statement is true so the code within the iteration is performed

At line 4, the values of temp is tested again

Is temp greater than 70?

Yes

At this point, the compiler prints "This porridge is too hot! " , Without the quotes

The next line performs arithmetic and assignment operation on temp

First, is temp greater than 150?

Yes

So, the arithmetic operations becomes

temp = 180 - 100 which gives 80

All other statements within the while iteration are then ignored

The compiler then test for the second time if temp is still not equal to 80.

Note that at this point, temp = 80

So, the test is false

All statements within the while iteration will then be ignored.

Program execution then moves to line 14.

Is temp = 80?

Yes

The compiler prints "This porridge is just right!" without the quotes.

User Xenology
by
4.8k points