Answers to Chapter 6 Review Questions

   


Chapter 6

1:

Why are there two ways to categorize the types in C#?

A:

The distinction "Simple types versus derived types" is used for historical reasons and because it is convenient, but it is strictly speaking not correct. In contrast "Value types versus reference types" is correct but perhaps less intuitive.

2:

Why does C# have other simple types than int?

A:

Different types are needed to represent different kinds of data.

3:

Which kind of attributes distinguish the different types from each other?

A:

The kind of data the type can represent, the memory use, the kind of operations in which it will take part, and in case it can hold simple numbers: the range and precision.

4:

What does it mean to be a strongly typed language like C#?

A:

A strongly typed language attempts to prohibit types from being involved in processes in which they are not meant to participate.

5:

Is it possible to assign a value of type int to a variable of type short, without an explicit conversion? Why or why not?

A:

No, because assigning a value of type int to a variable of type short potentially results in loss of magnitude. Any assignment with the potential risk of data loss (magnitude or precision) requires an explicit conversion.

6:

How do you specify a literal to be of type float?

A:

By appending an f (or F) to the number. Thus, 6.89f is a literal of type float.

7:

Write a line of code that declares a private instance variable called distance, which is of type float and is initialized to 100.5.

A:

private float distance = 100.5f;.

8:

A variable of type byte is holding the value 255. The program now attempts to increment the value by one. What happens: If the compiler switch is set to unchecked? If it is set to checked?

A:

If the compiler switch is set to unchecked, the variable overflows to make its value equal to 0. If it is set to checked a runtime error occurs.

9:

Which simple type would you use for a variable storing an arbitrary person's weight (in pounds)? (1 pound is approximately 0.45 kilos)?

A:

The simple type float.

10:

Which simple type would you use for storing account balances that would be involved in interest rate calculations requiring extremely high precision?

A:

The simple type decimal.

11:

Suppose myNumber and yourNumber are both of type float. Write a statement that adds these values together as ints and assigns them to an int variable.

A:

myIntValue = (int)myNumber + (int)yourNumber;.

12:

If number1 and number2 are of type int and text1 is of type string, what is the type of the following expression?

 number1 + text1 + number2 
A:

The expression is of type string.

13:

Is the following expression true or false when evaluated in C# and why? ((10 * 0.2f) == 2.0)

A:

0.2f is not exactly 0.2. This inaccuracy is exposed when (10 * 0.2f) is compared to a value of type double, such as 2.0, resulting in the expression to be false.

14:

When should you use constants in your source code? What are their advantages?

A:

Use constants when your source code contains values that are constant throughout the lifetime of the program. The advantages of using constants are

  • It is easier to understand the meaning of a name like Pi instead of a literal like 3.14.

  • The use of constants allow you to change a value in one place (where it is declared) rather than in every place it is used in the source code.

15:

Write a statement that prints 30000000.326m onscreen with this format: $30,000,000.33

A:

Console.WriteLine(30000000.326m.ToString("C"));.

Answers to Chapter 6 Programming Exercises

1:

Enable the clock to be adjusted by plus/minus 100 seconds by giving the commands H and M.

2:

A year on Blipos has 256 days. The first day of the year has number 0. The civilization is very old on Blipos; their current year is 4,294,967,296. Allow the Blipos clock to show the date on Blipos as ddd/y,yyy,yyy,yyy. Which types would you choose for ddd and yyyyyyyyyy?

3:

Allow the user to set and adjust the day and year of the Blipos clock so that it becomes possible to move forward and backward in time by one day and one year.

4:

The emperor's birthday is celebrated on the 100th day of each year. Enable the Blipos clock to write "Happy birthday emperor!" onscreen whenever the date is shown to be the 100th day of the year.

A:

The following source code provides answers to programming Exercises 1 4. The code parts related to a particular exercise have been marked with a comment, such as // Ex.1 or // Exercise 1.

 using System; class BliposClock {     private byte seconds;     private short minutes;      //Exercise 2     private byte days;     private ulong years;     public BliposClock()     {         seconds = 0;         minutes = 0;          // Exercise 2         days = 0;         years = 0;     }     public void OneForward()     {         byte originalSeconds = seconds;         short originalMinutes = minutes; //Ex. 2         byte originalDays = days; //Ex. 2         seconds++;         if (originalSeconds > seconds)              // Overflow of seconds variable             minutes++;          // Exercise 2         if (originalMinutes > minutes)              // Overflow of minutes variable             days++;         if (originalDays > days)              // Overflow of days variable             years++;     }     public void OneBackward()     {         byte originalSeconds = seconds;         short originalMinutes = minutes; //Ex. 2         byte originalDays = days; //Ex. 2         seconds--;         if (originalSeconds < seconds)              // Underflow of seconds variable             minutes--;          // Exercise 2         if (originalMinutes < minutes)              // Underflow of minutes variable             days--;         if (originalDays < days)              // Underflow of days variable             years--;     }     public void FastForward()     {         byte originalSeconds = seconds;         short originalMinutes = minutes; //Ex. 2         byte originalDays = days; //Ex. 2         seconds = (byte)(seconds + 50);         if (originalSeconds > seconds)              // Overflow of seconds variable             minutes++;          // Exercise 2         if (originalMinutes > minutes)              // Overflow of minutes variable             days++;         if (originalDays > days)              // Overflow of days variable             years++;     }     public void FastBackward()     {         byte originalSeconds = seconds;         short originalMinutes = minutes; //Ex. 2         byte originalDays = days; //Ex. 2         seconds = (byte)(seconds - 50);         if (originalSeconds < seconds)              // Underflow of seconds variable             minutes--;           // Exercise 2         if (originalMinutes < minutes)              // Underflow of minutes variable             days--;         if (originalDays < days)              // Underflow of days variable             years--;     }      // Exercise 1     public void HundredForward()     {         byte originalSeconds = seconds;         short originalMinutes = minutes; //Ex. 2         byte originalDays = days; //Ex. 2         seconds = (byte)(seconds + 100);         if (originalSeconds > seconds)              // Overflow of seconds variable             minutes++;          // Exercise 2         if (originalMinutes > minutes)              // Overflow of minutes variable             days++;         if (originalDays > days)              // Overflow of days variable             years++;     }      // Exercise 1     public void HundredBackward()     {         byte originalSeconds = seconds;         short originalMinutes = minutes; //Ex. 2         byte originalDays = days; //Ex. 2         seconds = (byte)(seconds - 100);         if (originalSeconds < seconds)              // Underflow of seconds variable             minutes--;          // Exercise 2         if (originalMinutes < minutes)              // Underflow of minutes variable             days--;         if (originalDays < days)              // Underflow of days variable             years--;     }     // Exercise 3     public void AddOneDay()     {         byte originalDays = days;         days++;         if (originalDays > days)              // Overflow of days variable             years++;     }      // Exercise 3     public void DeductOneDay()     {         byte originalDays = days;         days--;         if (originalDays < days)              // Underflow of days variable             years--;     }      // Exercise 3     public void AddOneYear()     {         years++;     }      // Exercise 3     public void DeductOneYear()     {         years--;     }     public void SetSeconds(byte sec)     {         seconds = sec;     }     public void SetMinutes(short min)     {         minutes = min;     }      // Exercise 2     public void SetDays(byte newDays)     {         days = newDays;     }      // Exercise 2     public void SetYears(ulong newYears)     {         years = newYears;     }     public void ShowTime()     {         Console.WriteLine("Sec: " + seconds + " Min: " + minutes);          // Exercise 2         Console.WriteLine("Day/year: " + days + "/" + years);          // Exercise 4         if (days == 100)             Console.WriteLine("Happy Birthday Emperor!");     } } class RunBliposClock {     public static void Main()     {         string command;         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: ");         myClock.SetSeconds(Convert.ToByte(Console.ReadLine()));         Console.Write("Enter Minutes: ");         myClock.SetMinutes(Convert.ToInt16(Console.ReadLine()));         Console.Write("Enter Days: "); //Ex.2         myClock.SetDays(Convert.ToByte(Console.ReadLine())); //Ex.2         Console.Write("Enter Years: "); //Ex.2         myClock.SetYears(Convert.ToUInt64(Console.ReadLine())); //Ex.2         Console.WriteLine("Enter command: F) Forward B) Backward " +             "A) Add fifty ");         Console.WriteLine("D) Deduct fifty H) Add hundred " + //Ex.1             "M) Deduct hundred "); //Ex.1         Console.WriteLine("Q) Add one Day  Y) Add one year " + //Ex.3             "U) Deduct one day\n  W) Deduct one year  T) Terminate"); //Ex.3         do         {             command = Console.ReadLine().ToUpper();             if (command == "F")                 myClock.OneForward();             if (command == "B")                 myClock.OneBackward();             if(command == "A")                 myClock.FastForward();             if(command == "D")                 myClock.FastBackward();              //Exercise 1             if(command == "H")                 myClock.HundredForward();             if(command == "M")                 myClock.HundredBackward();              //Exercise 3             if(command == "Q")                 myClock.AddOneDay();             if(command == "Y")                 myClock.AddOneYear();             if(command == "U")                 myClock.DeductOneDay();             if(command == "W")                 myClock.DeductOneYear();             myClock.ShowTime();         }  while (command != "T");         Console.WriteLine("Thank you for using the Blipos Clock");     } } 
5:

Write a program containing a method called AverageAge that calculates the average of three ages provided to it as arguments. Enable the user to enter three ages (as whole numbers) and use AverageAge to calculate the average age and print the result with a precision of three decimals. Which return type would you use for AverageAge? How can you format the output?

A:

The following source code constitutes the answer to Exercise 5.

 using System; class AgeCalculator {     public double AverageAge(byte age1, byte age2, byte age3)     {         double average;         average = (double)(age1 + age2 + age3) / 3;         return average;     } } class Tester {     public static void Main()     {         byte ageA;         byte ageB;         byte ageC;         AgeCalculator myCalculator = new AgeCalculator();         Console.Write("Enter age 1: ");         ageA = Convert.ToByte(Console.ReadLine());         Console.Write("Enter age 2: ");         ageB = Convert.ToByte(Console.ReadLine());         Console.Write("Enter age 3: ");         ageC = Convert.ToByte(Console.ReadLine());         Console.WriteLine("Average age: " +             myCalculator.AverageAge(ageA, ageB, ageC).ToString("N3"));     } } 


   


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

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