Chapter 4: Operators

Quiz

Solution to Question 4–1.

The output of the operations is:

32
6
4
Solution to Question 4–2.

The expressions evaluate to:

True
True
False
5
True

The fourth expression evaluates to 5, not to true. Thus, if you write:

z = x = y;

and y has the value 5, then the order of operations is that the value in y (5) is assigned to x, and the value of the expression x=y, which is 5, is assigned to z.

Solution to Question 4–3.

The prefix operator increments 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 the original value.

Solution to Question 4–4.

The correct order of operations is:

++
%
!=
&&
?:

Exercises

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.

namespace operators
{
   class exercise
   {
      static void Main(  )
      {
         int x = 25;
         int y = 5;
         System.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?

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

The output looks like this:

A: 6, B: 7, C: 6
Solution to Exercise 4-3.

Write a program that demonstrates the difference between the prefix and postfix operators.

namespace operators
{
   class exercise
   {
      static void Main(  )
      {
         int myInt = 5;
         int myOtherInt = myInt;
         System.Console.WriteLine("initial values: myInt: {0},
            myOtherInt: {1}
", myInt, myOtherInt);

         // prefix evaluation
         myOtherInt = ++myInt;
         System.Console.WriteLine("prefix evaluation myInt: {0},
            myOtherInt: {1}
", myInt, myOtherInt);

         // postfix evaluation
         myInt = 5;
         myOtherInt = 5;
         myOtherInt = myInt++;
         System.Console.WriteLine("postfix evaluation myInt: {0},
            myOtherInt: {1}
", myInt, myOtherInt);
      }
   }
}

The output looks like this:

initial values: myInt: 5, myOtherInt: 5
prefix evaluation myInt: 6, myOtherInt: 6
postfix evaluation myInt: 6, myOtherInt: 5
..................Content has been hidden....................

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