Chapter 4: Operators

Quiz Solutions

Solution to Question 4-1. The = operator is the assignment operator, used to assign a value to a variable. The == operator is the equality operator, which tests the equality of two values and returns a Boolean. Confusing the two is a very common mistake, and a common source of errors.

Solution to Question 4-2. To assign the same value to multiple variables, simply chain the assignments, like this:

int a = b = c = d = 36;

Solution to Question 4-3. When you divide two doubles, the solution has a fractional portion, expressed as a decimal, as you would expect. When you divide two ints, the compiler discards any fractional remainder.

Solution to Question 4-4. The purpose of the % operator is to return the remainder from an integer division. It’s very useful in controlling loops, as you’ll see later.

Solution to Question 4-5. The output of the operations is:

  • 32

  • 6

  • 4 (Be careful of the order of operations here; the division (8 / 4) takes place before the addition and the subtraction)

Be sure to take note of the parentheses and the order of operator precedence, as discussed in Operator Precedence.

Solution to Question 4-6. Because the self-assignment operators are used here, the value of myInt changes with each step, forming a new input for the next step.

myInt += 5;
myInt = 30
myInt -= 15;
myInt = 15
myInt *= 4;
myInt = 60
myInt /= 3;
myInt = 20

Solution to Question 4-7. The prefix operator increments (or decrements) the original value, and then assigns the new value to the result. The postfix operator assigns the original value to the result, and then increments (or decrements) the original value.

Solution to Question 4-8. The expressions evaluate to:

  1. True

  2. True

  3. False

  4. 5 (This expression evaluates to 5, not to true; remember that assignment returns the value assigned)

Solution to Question 4-9. The expressions evaluate to:

  1. True. x > y is true, and y < x is also true, so the entire expression is true.

  2. False. x > y is true, so !(x > y) is false.

  3. True. x < y is false, so !(x < y) is true. !(x < y) is true, and (x > y) is also true, so the entire expression together is true. Note that the ! is evaluated before the &&.

  4. True. This one is tricky, because of the nested parentheses, but if you take it one step at a time, you can work it out. (x > y) is true, and !(x < y) is also true, so ((x > y) || !(x < y)) all evaluates to true. The other side of the &&, (x > y), is also true, so you end up with true && true, which evaluates to true. As you can see, you need to be very careful how you nest your parentheses.

  5. False. The parentheses in this expression could drive you mad, but you don’t actually need to bother with them. Take a look at the second half of the expression, on the right side of the &&. You’ll see (x == y). You know that (x == y) is false. Because anything && false evaluates to false, you don’t need to bother with that nest of parentheses on the left. No matter what the left side evaluates to, the whole expression will be false. This is called short-circuit evaluation.

Solution to Question 4-10. The correct order of operations is:

++
%
!=
&&
?:

Exercise Solutions

Solution to Exercise 4-1. Write a program that assigns the value 25 to variable x, and 5 to variable y. Output the sum, difference, product, quotient, and modulus of x and y.

As always, there are a variety of ways to accomplish this task. However you do it, though, you must start by assigning two variables, x and y. From there, you could use temporary variables to hold each of the values you calculate, and output them all in a WriteLine( ) statement. Or you could just do the math in the WriteLine( ), as shown in Example A-6.

Example A-6. One solution to Exercise 4-1

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

namespace Exercise_4_1
{
   class Program
   {
      static void Main(  )
      {
         int x = 25;
         int y = 5;
         Console.WriteLine("sum: {0}, difference: {1}, product: {2},
                           quotient: {3}, modulus: {4}.", x + y, x - y,
                           x * y, x / y, x % y);
      }
   }
}

The output looks like this:

sum: 30, difference: 20, product: 125, quotient: 5, modulus: 0.

Solution to Exercise 4-2. What will be the output of the following method? Why?

static void Main(  )
{
   int varA = 5;
   int varB = ++varA;
   int varC = varB++;
   Console.WriteLine( "A: {0}, B: {1}, C: {2}", varA, varB, varC );
}

Of course, you could simply type in this code and see what the output is, but that won’t tell you why the output is what it is. Let’s start with the output:

A: 6, B: 7, C: 6

Now let’s take this apart one line at a time. The first line is simple enough:

int varA = 5;

You’ve set varA to 5. No problem:

int varB = ++varA;

The trick now is that actually two things are going on in this line. First, varA is incremented, from 5 to 6. Because you’re using the prefix operator, the increment happens before the assignment. Second, varB is set to the new value of varA, which is 6. So, at the moment, both varA and varB are 6:

int varC = varB++;

Again, two things are happening here. This time, because you’re using the postfix operator, the assignment happens first—varC is set equal to the current value of varB, which is 6. Then varB is incremented to 7, but the value of varC has already been assigned, so it doesn’t change. Therefore, when you get to the output, varA is 6, varB is 7, and varC is 6.

The lesson here is that if you want to set varB to be one more than varA, just use this:

varB = varA + 1;

instead of trying to save keystrokes with the increment operators. No matter how many keystrokes it saves, code is useful only if you can understand what it does.

Solution to Exercise 4-3. Imagine an amusement park ride that holds two passengers. Because of safety restrictions, the combined weight of the two passengers must be more than 100 pounds, but no more than 300 pounds. Now imagine a family of four who want to ride this ride. Abby weighs 135 pounds, Bob weighs 175 pounds, their son Charlie weighs 55 pounds, and their daughter Dawn weighs 45 pounds.

Write a program that calculates whether the weight of the two combined passengers falls within the accepted range. Use constants for the maximum and minimum weights, and for the weight of each family member. The output should look something like this, for Abby and Dawn:

Abby and Dawn can ride? True

Calculate three separate cases: whether the two parents can ride together, just Bob and Charlie, and just the kids.

As always, there are several ways to solve this problem. No matter what you choose, though, you need to determine whether the combined weight of the two passengers is between the maximum and minimum weights. The obvious choice for this is to use a logical and, like this:

bool canRide = ((weight1 + weight2) > minWeight) &&
((weight1 + weight2) <= maxWeight);

The bool canRide will be true only if the combined weight is both greater than the minimum weight and less than the maximum weight.

If you had access to user input and looping statements, you could make this application much fancier, but you’ll learn about those in the next chapter. Example A-7 shows one solution that fits the requirements.

Example A-7. One solution to Exercise 4-3

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

namespace Exercise_4_3
{
   class Program
   {
      static void Main(string[] args)
      {
         const int weightAbby = 135;
         const int weightBob = 175;
         const int weightCharlie = 55;
         const int weightDawn = 45;
         const int minWeight = 100;
         const int maxWeight = 300;

         bool canRide;
         int weight1, weight2;

         // Abby + Bob
         weight1 = weightAbby;
         weight2 = weightBob;
         canRide = ((weight1 + weight2) > minWeight) &&
                   ((weight1 + weight2) <= maxWeight);
         Console.WriteLine("Abby and Bob can ride? {0}", canRide);

         // Bob + Charlie
         weight1 = weightBob;
         weight2 = weightCharlie;
         canRide = ((weight1 + weight2) > minWeight) &&
                   ((weight1 + weight2) <= maxWeight);
         Console.WriteLine("Bob and Charlie can ride? {0}", canRide);

         // Charlie + Dawn
         weight1 = weightCharlie;
         weight2 = weightDawn;
         canRide = ((weight1 + weight2) > minWeight) &&
                   ((weight1 + weight2) <= maxWeight);
         Console.WriteLine("Charlie and Dawn can ride? {0}", canRide);

      }
   }
}

Solution to Exercise 4-4. Now it’s time for a little high school math. Take a sphere of radius 5. Calculate and output the surface area, and the volume of the sphere. Then use the ternary operator to indicate which of the two is greater. Make Pi a constant float, and use a value of 3.14159 for precision. You should probably also make the radius a constant.

This application isn’t too difficult, but it does require that you remember some math formulas (or know where to look them up online). The formula for the surface area of a sphere is 4πr2, and the formula for the volume is 4/3πr3. C# doesn’t have a built-in operator for raising to a power, so you can simply multiply the radius by itself two or three times, as needed.

To calculate the radius, you’d need something like this:

float surfaceArea = 4f * Pi * (radius * radius);

To calculate the surface area, you’d need something like this:

float volume = (4f / 3f) * Pi * (radius * radius * radius);

Note that you need to use the f suffix on the float values. It’s not strictly necessary on the 4 in the surface area calculation, but it’s crucial in the volume calculation. Remember that (4/3) is 1.33333 in floating-point division, but it’s just 1 in integer division.

The ternary operator isn’t difficult; just compare the two values and assign the larger one to a variable, which you can then output. (We do know that the surface area is in square units, and the volume is in cubic units, so you can’t really compare the two numbers, but we’ll overlook that for the purpose of this exercise.)

One solution is shown in Example A-8.

Example A-8. One solution to Exercise 4-4

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

namespace Exercise_4_4
{
   class Program
   {
      static void Main(  )
      {
         const float Pi = 3.14159f;
         const float radius = 5f;
         float surfaceArea = 4f * Pi * (radius * radius);
         Console.WriteLine("Surface area is: {0}", surfaceArea);
         float volume = (4f / 3f) * Pi * (radius * radius * radius);
         Console.WriteLine("Volume is: {0}", volume);
         float greater = surfaceArea > volume ? surfaceArea : volume;
         Console.WriteLine("The greater of these is: {0}", greater);

      }
   }
}
..................Content has been hidden....................

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