O'Reilly logo

Learning C# 2005, 2nd Edition by Brian MacDonald, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 5: Branching

Quiz

Solution to Question 5–1.

if, else, switch.

Solution to Question 5–2.

False. In C#, an if statement’s condition must evaluate to a Boolean expression.

Solution to Question 5–3.

The braces make maintenance easier. If you add a second statement later, you are less likely to create a logic error because it is obvious what “block” of statements the if refers to.

Solution to Question 5–4.

Either a numeric value or a string.

Solution to Question 5–5.

False. If the statement has no body, then you can fall through. For example:

case morning:
case afternoon:
      someAction(  );
      break;
Solution to Question 5–6.

Two uses of goto are:

  • To go to a label in your code

  • To go to a different case statement in a switch statement

Solution to Question 5–7.

do...while evaluates its condition is at the end of the statement rather than at the beginning, and thus is guaranteed to run at least once.

Solution to Question 5–8.

In a loop, it causes the remainder of the body of the loop to be skipped and the next iteration of the loop to begin immediately.

Solution to Question 5–9.

Two ways of creating an infinite loop are:

for (;;)
while(true)

Exercises

Solution to Exercise 5-1.

Create a method that counts from 1-10 using each of the while, do...while, and for statements.

using System; class Exercises { static void Main( ) { Console.WriteLine( "while" ); int counter = 1; while ( counter <= 10 ) { Console.Write( counter ); if ( counter < 10 ) { Console.Write( ", " ); } ++counter; } Console.WriteLine( "\nDo..while" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required