Chapter 5: Branching

Quiz Solutions

Solution to Question 5-1. The if, if…else, and switch statements are used for conditional branching.

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 can be placed in a switch statement.

Solution to Question 5-5. False. If the statement has no body, 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 at the end of the loop rather than at the beginning, and thus is guaranteed to run at least once.

Solution to Question 5-8. The header of a for loop includes the initializer, in which you create and initialize the counter variable; the expression, in which you test the value of the counter variable; and the iterator, in which you update the value of the counter variable. All three parts are optional.

Solution to Question 5-9. In a loop, the continue keyword 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-10. Two ways of creating an infinite loop are:

for (;;)
while(true)

Exercise Solutions

Solution to Exercise 5-1. Create a program that counts from 1 to 10 three times, using the while, do…while, and for statements, and outputs the results to the screen.

There’s nothing tricky about this exercise; you’re simply using each of the three loop types to count to 10. Remember to initialize your counter at 1 for each loop, and to set the condition to be counter <= 10, rather than counter < 10, or you’ll find your loop stopping at 9. If you want to be fancy, you can output on one line, using Write( ), and include an if statement to add a comma after each number except the last, as we’ve done here. Example A-9 shows the code.

Example A-9. One solution to Exercise 5-1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exercise_5_1
{
   class Program
   {
      static void Main(  )
      {
         Console.WriteLine( "while" );
         int counter = 1;
         while ( counter <= 10 )
         {
            Console.Write( counter );
            if ( counter < 10 )
            {
               Console.Write( ", " );
            }
            counter++;
         }
         Console.WriteLine( "
do..while" );
         counter = 1;
         do
         {
            Console.Write( counter );
            if ( counter < 10 )
            {
               Console.Write( ", " );
            }
            counter++;
         } while ( counter <= 10 );
         Console.WriteLine( "
for" );
         for ( int ctr = 1; ctr <= 10; ctr++ )
         {
            Console.Write( ctr );
            if ( ctr < 10 )
            {
               Console.Write( ", " );
            }
         }
         Console.WriteLine( "
Done" );
      }
   }
}

Solution to Exercise 5-2. Create a program that accepts an integer from the user as input, then evaluates whether that input is zero, odd or even, a multiple of 10, or too large (more than 100) by using multiple levels of if statements.

The solution to this exercise is going to be a rat’s nest of if statements, no matter what you do. However, the order in which you make the tests is critical. First, you need to test whether the number is too large (more than 100), because if it is, you stop right there. Inside that if, you check whether it’s odd or even, because if it’s odd, you stop there too. Inside the second if, you check whether it’s zero. Inside that, you check whether it’s a multiple of 10. That’s how you get four levels of if, and some very nasty code. Example A-10 shows one way to do it.

Example A-10. One solution to Exercise 5-2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exercise_5_2
{
    class Program
    {
        static void Main(  )
        {
            while (true)
            {
                Console.Write("Enter a number please: ");
                string theEntry = Console.ReadLine(  );
                int theNumber = Convert.ToInt32(theEntry);

                // Logic: if the number is greater than 100, say it is too big
                // if it is even but not a multiple of 10 say it is even
                // if it is a multiple of 10, say so
                // if it is not even, say it is odd
                if (theNumber <= 100)
                {
                    if (theNumber % 2 == 0)
                    {
                        if (theNumber == 0)
                        {
                            Console.WriteLine("Zero is not even or odd or a
                                               multiple of 10");
                        }
                        else
                        {
                            if (theNumber % 10 == 0)
                            {
                                Console.WriteLine("You have picked a multiple
                                                   of 10");
                            }
                            else
                            {
                                Console.WriteLine("Your number is even");
                            }  // end else not a multiple of 10
                        }  // end else not zero
                    }  // end if even
                    else
                    {
                        Console.WriteLine("What an odd number to enter");
                    }
                }  // end if not too big
                else
                {
                    Console.WriteLine("Your number is too big for me.");
                }
            } // end while
        }
    }
}

Solution to Exercise 5-3. Rewrite the program from Exercise 5-2 to do the same work with a switchstatement.

The switch statement makes a nice alternative to programs that have lots of nested if statements. To rewrite the program using a switch, you first have to define an enum that outlines the various possibilities. Then you’ll need a series of (nonnested) if statements to determine which of the enum options applies. Once you’ve done that, you can use a switch to output the appropriate statement, and even include a default that accounts for unexpected input. One solution is shown in Example A-11.

Example A-11. One solution to Exercise 5-3

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exercise_5_3
{
   class Program
   {
      enum numericCondition
      {
         even,
         multiple,
         odd,
         tooBig,
         unknown,
         zero
      }
      static void Main(  )
      {
         while (true)
         {
            Console.Write("Enter a number, please: ");
            string theEntry = Console.ReadLine(  );
            int theNumber = Convert.ToInt32(theEntry);

            numericCondition condition = numericCondition.unknown;  // initialize
            condition = (theNumber % 2 == 0) ?
                        numericCondition.even : numericCondition.odd;
            if (theNumber % 10 == 0) condition = numericCondition.multiple;
            if (theNumber == 0) condition = numericCondition.zero;
            if (theNumber > 100) condition = numericCondition.tooBig;
            // switch on the condition and display the correct message
            switch (condition)
            {
               case numericCondition.even:
                  Console.WriteLine("Your number is even");
                  break;
               case numericCondition.multiple:
                  Console.WriteLine("You have picked a multiple of 10");
                  break;
               case numericCondition.odd:
                  Console.WriteLine("What an odd number to enter");
                  break;
               case numericCondition.tooBig:
                  Console.WriteLine("Your number is too big for me.");
                  break;
               case numericCondition.zero:
                  Console.WriteLine("zero is not even or odd
                                     or a multiple of 10");
                  break;
               default:
                  Console.WriteLine("I'm sorry, I didn't understand that.");
                  break;
            }
         }
      }
   }
}

You could make the case that this solution is more complicated than Example A-10. After all, you still have a bunch of if statements to set the value of the enum, even if they’re not nested. And the solution here is obviously longer than Example A-10. However, we believe that the switch statement used here is easier to read and maintain, which may take a bit longer to write now, but will save you time in the future.

Solution to Exercise 5-4. Create a program that initializes a variable i at 0 and counts up, and initializes a second variable j at 25 and counts down. Use a for loop to increment i and decrement j simultaneously. When i is greater than j, end the loop and print out the message “Crossed over!”

This exercise is tricky. It’s possible to use two counter variables in the header of a for loop, although it’s not commonly done. In this case, you need to declare i and j before starting the loop. Then, in the header, you initialize i to 0 and j to 25. You want the loop to end when i has become less than j, so your condition is simple: i < j. You want i to count up and j to count down, so for your iterator, you use i++ and j--. As soon as i becomes less than j, the loop ends, so you output the final message outside the loop. Example A-12 shows one possible solution.

Example A-12. One solution to Exercise 5-4

namespace Exercise_5_4
{
   class Program
   {
      static void Main(  )
      {
         int i;
         int j;
         for (i = 0, j = 25; i < j; ++i, --j )
         {
            Console.WriteLine("i: {0}; j: {1}", i, j);
         }
         Console.WriteLine( "Crossed over! i: {0}; j: {1}", i, j );
      }
   }
}

The output looks like this:

i: 0; j: 25
i: 1; j: 24
i: 2; j: 23
i: 3; j: 22
i: 4; j: 21
i: 5; j: 20
i: 6; j: 19
i: 7; j: 18
i: 8; j: 17
i: 9; j: 16
i: 10; j: 15
i: 11; j: 14
i: 12; j: 13
Crossed over! i: 13; j: 12
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset