next up previous
Up: APS105 Home Page

UNIVERSITY OF TORONTO
FACULTY OF APPLIED SCIENCE AND ENGINEERING
APS105F -- Computer Fundamentals
Midterm Test #1, October 2nd, 2000
Examiners - John Carter, G. Lemieux, James MacLean

Duration 1.5 hours


Circle your lecture section:         L0101        or        L0102        or        L0103


Name


Student Number


ECF Login


MARKS


Question #     1     2     3     4     5     6     7     8     9    10    11    12 TOTAL
Value 15 5 10 6 9 5 5 5 10 10 10 10 100
                           
Mark                          
                           

1.
(15 Marks) Circle the correct answer for each of the following:

(a)
True or \framebox{\bf False} The int data type is the largest primitive data type in Java.
The long type is bigger.

(b)
True or \framebox{\bf False} The Java data type long can represent any integer.
Some integers are still too big for long.

(c)
True or \framebox{\bf False} The && operator has higher priority than <.

(d)
\framebox{\bf True} or False 4.0 * 16 / 11 - 2 > 3

(e)
\framebox{\bf True} or False Assuming a, b and c are of type int, there is a syntax error in this
Java statement: a = b = !c;

(f)
\framebox{\bf True} or False Any for loop can always be rewritten as a while loop.

(g)
True or \framebox{\bf False} Poor indentation style will make it difficult to compile your program.
The compiler doesn't care.

(h)
\framebox{\bf True} or False Comments are useful to explain how a complex sequence of code works.

(i)
True or \framebox{\bf False} Java converts expressions between floating-point and integer data types
as needed. Conversion only goes one-way.

(j)
True or \framebox{\bf False} The expression Math.floor(x) < Math.ceil(x); is true for
all values of x. Not true for integer values of x.

(k)
\framebox{\bf True} or False An expression containing only numbers and operators can evaluate to a
boolean data type. Example: 3 != 5.

(l)
True or \framebox{\bf False} Lazy evaluation refers to the fact that Java will only execute one of
a = b; or b = a; in the code below, but never both:
              if( a < b )
                  a = b;
              else
                  b = a;

Lazy evaluation refers to not evaluating both operands
of an && or || expression, not to if statements.

(m)
True or \framebox{\bf False} Java is a low-level language and is not suitable for professional use.

(n)
True or \framebox{\bf False} Numerical variables do not need to be initialized, they default to zero.

(o)
True or \framebox{\bf False} Computer programs always generate correct answers.
Overflows can cause incorrect results.

2.
(5 marks) Assuming that i and j are int variables whose values are 8 and 5 respectively, show the output that would be produced by the following statements. (Print one character in each space provided.)
(a)
System.out.println("Sum is: " + i + j);
Sum is: 85




(b)
System.out.println("Quotient" + i/j);
Quotient1





(c)
System.out.println("\"mod\" " + i%j);
"mod" 3




3.
(10 marks) The following program contains ten known syntax errors. Find and correct them in the body of the program.
class BadExample
{
public static  
\framebox{void}  main (String[] args)
{
boolean done = false;

while  
\framebox{( !}  done)
{
System.out.println( 
\framebox{\tt ''} Give a value - zero to stop");

\framebox{int}  value = Stdin.getInt();

if  
\framebox{(}  value   \framebox{==}  0   \framebox{)}
done = true  
\framebox{;}
else
System.out.println(value + " " +  
\framebox{Math.}sqrt(value)   \framebox{)} ;
 
\framebox{\}}
}
}

4.
(6 Marks) Give the Unix commands required to:
(a)
Delete the file Hello.class.



rm Hello.class

(b)
Edit the file Hello.java. Any of:



nedit Hello.java
vi Hello.java
emacs Hello.java
pico Hello.java


(c)
Compile and run the program in Hello.java. Both of:



javac Hello.java
java Hello


5.
(9 marks) Give a very short answer to each of the following:
(a)
Name 3 important computer parts and describe briefly (one line max) what each does.
i.
CPU is responsible for arithmetic computation and control
ii.
memory holds the state of the computer, including programs and data
iii.
I/O is responsible for interacting with the outside world, eg keyboard and screen

(b)
What is the difference between machine code and Java bytecode?
Machine code is the native language of a CPU, and is unique to each one.
Java bytecode is a special type of machinecode designed for the
Java Virtual Machine (JVM), whch is design to run on any processor.

(c)
Why does Java have four different types of integers?
There are times when you don't need the full range of values provided
by long and you need to save space (memory).

(d)
What is the error in the following statements? Explain.
double y = 3.14159265;
float x = 2 * y;
The result of 2 * y is a double value, and this cannot be
assigned to a float in Java. You must do a type cast, since the
float variable may overflow when assigning a double
value to it.

6.
(5 marks) Given integer variables x, y and z, write a Boolean expression which is true only when all of the following are true:

Notice the order below -- we are using lazy evaluation to protect against the divide-by-zero error.

     x >= 0   &&   z != 0   &&   x > y / z   &&   z%2 == 0

7.
(5 marks) What does the following Java program print?
class MyProg
{
  public static void main(String [] args)
  {
    int a = 12, b = 3, c = 5 ;

    System.out.println("start");
    if (b>c)
      for (int i = c; i <= b; i++)
        if (c < a) System.out.println(c);
    else
      while (a > 0) 
      {
        System.out.println(a--);
      }
    System.out.println("finish");
  }
}
Indentation doesn't matter. Since the else is associated with the most recent if, this program prints:
start
finish

8.
(5 Marks) Rewrite the following for loop as a while loop.
         int i, sum;
         int n = Stdin.getInt();
         sum = 0;
         for( i = 1; i <= n; i = i * 2 ) {
           sum = sum + i;
         }




         int i, sum;
         int n = Stdin.getInt();
         sum = 0;
         i = 1;
         while( i <= n ) {
             sum = sum + i;
             i = i * 2;
         }

9.
(10 marks) Write a Java program that reads three pairs of integer numbers, x1,y1, x2, y2 and x3,y3. Each pair of numbers represents a point in a plane. Your program is to determine if the three points are co-linear or not, and output its decision.

class Colinear
{
    public static void main(String[] args)
    {
       int x1 = Stdin.getInt();
       int y1 = Stdin.getInt();
       int x2 = Stdin.getInt();
       int y2 = Stdin.getInt();
       int x3 = Stdin.getInt();
       int y3 = Stdin.getInt();

       // compare the slopes between points 1 to 3 versus 1 to 2
       // if the slopes are equal, they must be colinear (because
       // they share at least 1 as a common point).
       // we must therefore test the following:
       //            slope12 == slope13
       //
       // which is just:
       //              y2-y1    y3-y1
       //              ----- == -----
       //              x2-x1    x3-x1
       //
       // or, after cross multiplying, the test becomes:
       //  (x3-x1) * (y2-y1) == (y3-y1) * (x2-x1)
       //
       // note this can be done with just integers
       // (we'll ignore the chances of overflow)
       int  leftSide = (x3-x1) * (y2-y1);
       int rightSide = (x2-x1) * (y3-y1);

       if( leftSide == rightSide )
          System.out.println("colinear");
       else
          System.out.println("not colinear");
    }
}

10.
(10 marks) Write a complete Java program that first asks the user (repeatedly, if necessary) for a positive integer. Once the user has provided such an integer, the program then prints a diagonal pattern with that number of asterisks and quits. The diagram below shows the pattern that should be produced with input of 5.
*
 *
  *
   *
    *

class Stars
{
    public static void main(String[] args)
    {

       int n;

       do {
          System.out.println("Please enter a positive integer");
          n = Stdin.getInt();
       } while( n <= 0 );

       for( int row = 0; row < n; row++ ) {

           for( int spaces=0; spaces<row; spaces++ ) {
               System.out.print(" ");
           }

           System.out.println("*");

       }

    }
}

11.
(10 Marks) The following program lacks both comments and meaningful identifiers. Determine the purpose of the program. Rename the identifiers in the underlined spaces provided and add appropriate comments to convey greater meaning to the program. Note: The //'s indicate where comments are required, but not how many lines of comments you need to write.

// This program ...  asks the user to guess the largest prime
// number they can.  It continues until a non-prime is guessed,
// after which it prints the largest prime entered.
//
//
class Z                 // new identifier: Z___LargestPrime______
{
  public static void main(String[] args)
  {
    int     A;          // new identifier: A____userGuess________
    boolean B;          // new identifier: B____isGuessPrime_____
    int     C = 1;      // new identifier: C____largestPrime_____
    int     D;          // new identifier: D____divisor__________

    do {

      // Get a value >= 2 from the user
      //
      System.out.println("Guess a number:");
      do {
        A = Stdin.getInt();
      } while( A < 2 );

      // Test if the userGuess is prime, by first assuming it is prime.
      // We will change our minds if we find a divisor.
      B = true;
      for( D=2; D < A; D++ )
        if( A % D == 0 )            //  we found a divisor
          B = false;                //  it cannot be prime

      // guess was successful, tell the user
      //
      if( B ) {
        // remember the largest prime guessed
        //
        if( A > C ) {
           System.out.println("yes! good guess, you're getting better!");
           C = A;
        } else {
           System.out.println("yes! good guess, but not good enough!");
        }
      }

    } while( B );

    System.out.println("sorry, bad guess, but the best C was:");
    System.out.println( C );
  }
}

12.
(10 Marks) Two numbers are said to be relatively prime if they share no common factors other than the number 1. Write a Java program to ask the user for two numbers, then determine whether they are relatively prime. For example, $35 = 5 \times 7$ and $66 = 2 \times 3 \times 11$ are relatively prime.

class RelativelyPrime
{
    public static void main(String[] args)
    {
       int x = Stdin.getInt();
       int y = Stdin.getInt();

       int smaller;
       if( x < y ) {
           smaller = x;
       } else {
           smaller = y;
       }

       // test all possible divisors, see if they factor
       // we only have to test up to the smaller number
       boolean isRelativelyPrime = true;
       for( int divisor=2; divisor <= smaller; divisor++ ) {

           // done as soon as we find one divisor of both
           if( x % divisor == 0  && y % divisor == 0 ) {
               isRelativelyPrime = false;
               break;
           }

       }

       if( isRelativelyPrime )
            System.out.println("They are relatively prime.");
       else {
            System.out.print  ("They are not relatively prime.");
            System.out.print  ("They share the factor " )
            System.out.println( divisor + "." );
       }

    }
}


next up previous
Up: APS105 Home Page
Guy G. Lemieux
2000-10-16