Test Your Knowledge: Exercises

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.

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 );
}

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.

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.

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.