CS101 Algorithms and Programming I - Section: 03 - Quizzes

Quiz 1 (10 Feb 2016)

Question: Write a class that models a toy car, which can go only forwards and backwards.
  • The class should have a constructor, which takes “car speed” as an argument.
  • The class should have methods to go forwards and backwards, which take the “movement duration” as an argument.
  • The class should also have a method to get the current position.
  • Assume that
    • the “car speed” is in "meters per second”
    • the “movement duration” argument is in "seconds”
    • initial position of the car is 0
  • You may use double or int for the speed and movement duration arguments.
  • You are not required to write comments.
Answer
/**
   A toy car model.
 */
public class ToyCar { 
    /** 
       The speed of the car, in meters/second.
     */
    private double speed;

    /** 
       One-dimensional position of the car, in meters.
     */
    private double position;

    /** 
       Constructs a new car instance, with a spefied movement speed.
       @param carSpeed  The speed of the car, int meters/second.
     */
    public ToyCar(double carSpeed) {
        speed = carSpeed;
        position = 0;
    }

    /** 
       Move car forwards for a fixed duration of time.
       @param duration Movement duration in seconds.
     */
    public void goForwards(double duration) {
        position = position + duration * speed;
    }

    /** 
       Move car backwards for a fixed duration of time.
       @param duration Movement duration in seconds.
     */
    public void goBakwards(double duration) {
        position = position - duration * speed;
    }

    /** 
       Get the current position of the car, relative to the starting point.
       @return Current car position, in meters. 
     */
    public double getPosition() {
        return position;
    }
}

    

Quiz 2 (19 Feb 2016)

Question: Write a class, called "Converter", which provides conversion between USD and TRY currencies.
  • The class should have a constructor, which takes “the value of USD in TRY” (the conversion rate) as an argument.
  • The class should have two methods:
    • to convert USD to TRY
    • to convert TRY to USD
  • Write another class that uses Converter. In the main method, do the following:
    • declare a constant for USD-to-TRY conversion rate (eg, 3),
    • convert 5 USD to TRY, and print,
    • convert 18 TRY to USD, and print.
  • You are not required to write comments.
Answer
/**
  A utility class for conversion between the USD and TRY currencies.
 */
public class Converter {

    /** 
      The conversion rate.
     */
    private double rate;

    /** 
      Constructs a converter class with a given conversion rate.
      @param rate The conversion rate, ie. the value of 1 USD in TRY.
     */
    public Converter(double rate) {
        this.rate = rate;
    }

    /**
      Convert USD to TRY.
      @param amount The amount in USD to be converted.
     */
    public double convertUsdToTry(double amount) {
        return amount * rate;
    }

    /**
      Convert TRY to USD.
      @param amount The amount in TRY to be converted.
     */
    public double convertTryToUsd(double amount) {
        return amount / rate;
    }

}


/**
  A usage example for the Converter class.
 */
public class ConverterTester {
    public static void main(String [] args) {
        final double USD_TRY_RATE = 3; // any constant value is OK for grading
        Converter defaultConverter = new Converter(USD_TRY_RATE);
        System.out.print("5 USD in TRY: "); // not required in the question
        System.out.println(defaultConverter.convertUsdToTry(5));
        System.out.print("18 TRY in USD: "); // not required in the question
        System.out.println(defaultConverter.convertTryToUsd(18));
    }
}

    

Quiz 3 (11 Mar 2016)

Question: Write a main method that repeatedly prompts (asks) the age of a person in years. Each time the user enters the age, it should print baby OR child OR adult, according to the following rules:
  • age is less than 3 months: “baby”
  • age is 3 months or above, but less than 18 years: “child”
  • age is 18 years and above: “adult”
The program should automatically finish after running (prompting user and printing a message) 10 times.
Answer

import java.util.Scanner;

public class Q3 {
    public static void main( String [] args ) {
        Scanner in = new Scanner( System.in );
        int count = 0;
        while ( count < 10 ) {
            count++;
            System.out.print("Enter age: ");
            double age = in.nextDouble();
            if ( age >= 18 ) {
                System.out.println("adult");
            } else if ( age >= 0.25 ) {
                System.out.println("child");
            } else 
                System.out.println("baby");
            }
        }
    }
}

    

Quiz 4 (23 Mar 2016)

Question: Write a main method that prompts the user to enter the number of values to be read. If the number of values is greater than 0,
  • read numbers (as floating point numbers)
  • print their average
  • start from beginning, and prompt the user again
Otherwise, do not prompt the user again.
Answer
import java.util.Scanner;

public class Q4 {
    public static void main (String[] args) {
        Scanner in = new Scanner( System.in );
        int count = 1;
        while( count > 0 ) {
            System.out.print("The number of values to be read: "); 
            count = in.nextInt();
            double sum = 0;
            for (int j = 0; j < count; ++j) {
                System.out.print("Enter value: "); 
                sum = sum + in.nextDouble();
            }
            if ( count > 0 ) { 
                System.out.printf("Average: %.1f\n",sum/count); 
            }
        }
    } 
} 
    

Quiz 5 (30 Mar 2016)

Question:
Write a static method called 'squaredVectorNorm' that will compute the sum of square of each element in the input array.
The method should take an array of double values as an argument, and return the sum of squared elements.
If the number of input elements is zero, it should return 0.
For example, if input is [5 1 3], then the result is 35 (since 25+1+9=35).
Answer
    public static double squaredVectorNorm(double [] vec) {
        double res = 0;
        for ( int j = 0; j < vec.length; ++j ) {
            res += vec[j] * vec[j];
        }
        return res;
    }
    

Quiz 6 (13 Apr 2016)

Question:
Write a method called 'trace' that will return the sum of diagonal items in a given double matrix. The matrix is represented as a 2-d array, which is given as an argument.
Answer
    /**
     * Compute the sum of diagonal elements in a given matrix.
     *
     *  @param mat Matrix, represented as a 2D array.
     *
     *  @return The sum of diagonal elements.
     */
    public static double trace(double [][] mat) {
        double sum = 0;
        int nDiag = mat.length; // nrows
        if (mat.length > 0 && nDiag > mat[0].length) { // handle empty matrix
            nDiag = mat[0].length; // ncols
        }
        for ( int i = 0; i < nDiag; ++i ) {
            sum += mat[i][i];
        }
        return sum;
    }
    

Quiz 7 (22 Apr 2016)

Question:
Write the output of the following code snippet, using the given BankAccount class.
        BankAccount a1 = new BankAccount(100);
        BankAccount a2 = new BankAccount(500);
        BankAccount a3 = a1;
        a1.setAccountNumber(300);
        BankAccount a4 = new BankAccount(1000);
        System.out.println(a1);
        System.out.println(a2);
        System.out.println(a3);
        System.out.println(a4);
        
Answer
        Account: 300 balance: 100.0
        Account: 1002 balance: 500.0
        Account: 300 balance: 100.0
        Account: 1003 balance: 1000.0
    

Quiz 8 (27 Apr 2016)

Question:
Write the output of the following code snippet, using the given AccountManager class.
        AccountManager mng = new AccountManager();

        Account a1 = new Account("Joe");
        Account a2 = new Account("Marvin");
        Account a3 = a1;
        Account a4 = a3;

        mng.addAccount(a1);
        mng.addAccount(a2);
        mng.addAccount(a3);
        mng.addAccount(a4);

        mng.depositAll(10);
        a4.deposit(60);
        a3.deposit(100);
        a1.withdraw(10);
        mng.printAll();