CS71: Quiz 1 Study Guide

You are responsible for all material covered through the end of Week 3.


You should understand the following terms:



Sample practice problems:


  1. This code contains one or more errors. What are they?
int numItems = '4';
int[] values = new int[4];
for (int i = 0; i < numItems; i++)
{
   values[i] = 0;
}
  1. Consider the errors above. Can they be found at compile time found at runtime?

  2. The following program fails to compile. Why?

using System;

public static void Main()
{
   Console.WriteLine("Hello, World");
}
  1. Suppose we fix the above code. What commands can we use to compile and run it?

  2. Consider the code in question 3. Suppose Sally builds hello.exe on one of the lab linux machines. Can Billy run the executable on his windows laptop? Why or why not?

  3. The following class has bad encapsulation. Why?

class A
{
   public int a = 0;
   public A(int startVal)
   {
      a = startVal;
   }

   public int GetA()
   {
      return a;
   }
}
  1. How can we re-write the class in question 6 to have better encapsulation?

  2. What is the output of the following program?

class A
{
   protected int _value = 1;
   public A()
   {
   }

   public virtual int GetValue()
   {
      return _value;
   }
}

class B : A
{
   public B(int startVal)
   {
      _value = startVal;
   }

   public override int GetValue()
   {
      return _value * 2;
   }
}

class MainClass
{
   public static void Main()
   {
      A a1 = new A();
      A a2 = new B(2);

      Console.WriteLine("a1 has value: "+a1.GetValue());
      Console.WriteLine("a2 has value: "+a2.GetValue());
   }
}
  1. Consider the following method. Based on the principles of good and bad coding, what constructive critisms could you give to the following code? How might you re-write the code to make it clearer and more re-useable?
public static void Solve(double v1, double v2, double v3)
{
   if (v1 == 0) {
      Console.WriteLine("The value is "+(-v3/v2));
   }
   else
   {
      v1 = v1 * 2;
      double tmp = v2;
      v2 = v2 * v2 - 2 * v1 * v3;
      if (v2 > 0) {
         v2 = Math.Sqrt(v2);
         Console.WriteLine("The value is "+(-tmp + v2)/v1);
         Console.WriteLine("The value is "+(-tmp - v2)/v1);
      }
      else if (v2 == 0)
      {
         v2 = Math.Sqrt(v2);
         Console.WriteLine("The value is "+(-tmp)/v1);
      }
   }
}
  1. Consider the following method specification which tests whether a number is within a given interval. What partitions should we define for testing? Design a test suite which covers each part of your defined partitions.
// requires: startInterval <= endInterval
// effects: returns true if value is within the interval defined by [startInterval, endInterval]
// (inclusive!!) and false otherwise
bool inInterval(float value, float startInterval, float endInterval)