Answers to Chapter 7 Review Questions

   


Chapter 7

1:

How are the following expressions evaluated in C#:

  1. 5 + 10 * 2

  2. 5 * 6 / 3

  3. 12 / 4 * 6

  4. 20 % 8

  5. myIntVariable++

  6. --myIntVariable

A:
  1. 5 + (10 * 2) = 5 + 20 = 25

  2. (5 * 6) / 3 = 30 / 3 = 10

  3. (12 / 4) * 6 = 3 * 6 = 18

  4. 20 % 8 = 4

  5. The value of myIntVariable is incremented by one. If myIntVariable++ is part of a longer expression, this increment will take place after other operations in the expression.

  6. The value of myIntVariable is decremented by one. If --myIntVariable is part of a longer expression this decrement will take place before other operations in the expression.

2:

Suppose you need to add number1 and number2 together and multiply this result by number3. The first attempt:

 number1 + number2 * number3 

gave a wrong result. Fix the problem.

A:

Add a pair of parentheses, as in the following line:

 (number1 + number2) * number3 
3:

The following expression is correct but unclear for the reader of the code. Make it more clear.

 num1 + num2 / num3 * num4   num5 * num6 / num7 
A:
 (num1 + ((num2 / num3) * num4)) - ((num5 * num6) / num7) 
4:

Write an if statement that checks whether a number (call it myNumber) of type int is even or odd. Only if myNumber is even should it write "The number is even" onscreen.

A:
 if ((myNumber % 2) == 0)     Console.WriteLine("The number is even") 
5:

What is the type of the following expression if weight is of type short?

 -weight 
A:

It is of type int.

6:

Improve the clarity of the following statement by separating it into three statements without altering the effects of the code:

 totalBacteria = ++bacteriaInBody1 + bacteriaInBody2++; 
A:
 bacteriaInBody1++; totalBacteria = bacteriaInBody1 + bacteriaInBody2; bacteriaInBody2++; 
7:

Draw a flowchart that illustrates the following logic. A person wants to go for a walk. If it rains, he asks his wife if they have an umbrella. If they have an umbrella he will go out; otherwise, he will stay inside. If it does not rain, he will go out whether they have an umbrella or not.

A:
graphics/ainfig01.gif

8:

Which construct would be suitable to represent the following values in a C# program: { Red, Green, Blue, Yellow, Purple}

A:

The enumerator construct.

9:

Write a statement that prints the following text on the console (including the quotation marks)?

 And then he said: "This is a great moment" 
A:
 Console.WriteLine("And then he said:\ "This is a great moment\ ""); 
10:

Suppose myString contains 20 characters. Write an expression that returns a sub-string from myString beginning at character number 10 and including 5 characters.

A:
 myString.Substring(9,5) 
11:

Suppose distance1 is 100, distance2 is 200, and distance3 is 400. Write a statement that uses embedded formatted numbers to include the three variables in a string so that the final text reads

 The first distance is 100 meters, the second distance is 200 meters and the third distance is 400 meters. 
A:
 Console.WriteLine("The first distance is {0} meters, the second distance is {1} meters,  graphics/ccc.gifand the third distance is {2} meters", distance1, distance2, distance3); 

Answers to Chapter 7 Programming Exercises

1:

Apart from reporting every Sunday, it should also report every Saturday. Hint: At the moment, the program is detecting every 7, 14, 21, 28, and so on. Which numbers does it need to detect to find all the Saturdays? Those would be 6, 13, 20, 27, and so on. How do they relate to the Sunday numbers? How can this be implemented?

2:

Let's say that every year in the simulation has 365 days. Change the program to let it report the running time in days, weeks, and years, instead of just the days and weeks reported currently.

A:

The following source code contains answers to Exercises 1 and 2. The relevant parts are marked // Exercise 1 or // Ex. 1 or similar.

 using System; class DayCounter {     public static void Main()     {         uint dayCounter = 0;         uint maxSimulationDays;         uint weeks;         uint years; // Exercise 2         byte remainderDays;         byte remainderDaysSaturday; //Exercise 1         Console.Write("Please enter the number of days " +             "the simulation should run for ");         maxSimulationDays = Convert.ToUInt32(Console.ReadLine());         while(dayCounter < maxSimulationDays)         {             dayCounter++;             weeks = dayCounter / 7;             years = weeks / 52; //Exercise 2             remainderDays = (byte)(dayCounter % 7);              //Exercise 1             remainderDaysSaturday = (byte)((dayCounter + 1) % 7);              //Exercise 2             Console.WriteLine("Weeks: {0} Days: {1} Years: {2}",                 weeks - (years * 52), remainderDays, years);             if(remainderDays == 0)                  // TODO send "it's Sunday" message to controller                 Console.WriteLine("\t\tHey Hey It's Sunday!");              //Exercise 1             if(remainderDaysSaturday == 0)                 Console.WriteLine("\t\tHey It's Saturday");              // TODO start simulation lasting for one day.              // Let the program pause for 200 milliseconds             System.Threading.Thread.Sleep(200);         }         Console.WriteLine("Simulation ended");     } } 
3:

Recall the Blipos Clock case study in Chapter 6, "Types Part I: The Simple Types." Instead of relying on the overflow/underflow mechanism of the integer types, rewrite the BliposClock class to use the modulus operator to accomplish exactly the same tasks.

A:

The following source represents an answer to Exercise 3:

 using System; class BliposClock {      //A time in the BliposClock is represented by just one value: totalSeconds.      //All displayed times are derived from this basic value.     private ulong totalSeconds;     public BliposClock()     {         totalSeconds = 0;     }     public void AddSeconds(ulong secondsToAdd)     {         totalSeconds = totalSeconds + secondsToAdd;     }     public void DeductSeconds(ulong secondsToDeduct)     {         totalSeconds = totalSeconds - secondsToDeduct;     }      //initialMinutes can be between -32768 and 32767 so to convert this value      //to totalSeconds we must add 32768 and multiply by 256 before we add this      //value to initialSeconds as shown in the statement of the following method.     public void SetTime(byte initialSeconds, short initialMinutes)     {         totalSeconds = (ulong)initialSeconds + (ulong)((initialMinutes + 32768) * 256);     }     public void ShowTime()     {         byte secondsToShow;         int secondsPassedBy; // Total number of seconds the day is old         short minutesToShow;         secondsToShow = (byte)(totalSeconds % 256);         secondsPassedBy = (int)(totalSeconds % (256 * 65536));          //By dividing secondsPassedBy by 256 in the next line we find the          //number of whole minutes the day is old. This number can be          //between 0 and 65535. However we need a number          // between -32768 and 32767, which we can get by          //subtracting 32768 as shown in the next line.         minutesToShow = (short) ((secondsPassedBy / 256) - 32768);         Console.WriteLine("Sec: {0}   Min: {1}", secondsToShow, minutesToShow);     } } class RunBliposClock {     public static void Main()     {         string command;         byte tempSeconds;         short tempMinutes;         Console.WriteLine("Welcome to the Blipos Clock. " +             "256 seconds per minute " +             "65536 minutes per day");         BliposClock myClock = new BliposClock();         Console.WriteLine("Please set the clock");         Console.Write("Enter Seconds: ");         tempSeconds = Convert.ToByte(Console.ReadLine());         Console.Write("Enter minutes: ");         tempMinutes = Convert.ToInt16(Console.ReadLine());         myClock.SetTime(tempSeconds, tempMinutes);         Console.WriteLine("Enter (F)orward ackward " +             "(A)dd fifty educt fifty (T)erminate");         do         {             command = Console.ReadLine().ToUpper();             if (command == "F")                 myClock.AddSeconds(1);             if (command == "B")                 myClock.DeductSeconds(1);             if(command == "A")                 myClock.AddSeconds(50);             if(command == "D")                 myClock.DeductSeconds(50);             myClock.ShowTime();         }  while (command != "T");         Console.WriteLine("Thank you for using the Blipos Clock");     } } 


   


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net