CS210 ALGORITHMS & DATA STRUCTURES I

LABORATORY 1

30/09/05

Mr. T. Lysaght

REVISION OF JAVA

The purpose of this Laboratory session is Revision of Java concepts to include Fundamental Data Types, Class structure, Decision and Iteration, and Arrays.

  1. Let n be and integer and x a floating-point number.  Explain the difference between:

n = (int) (x + 0.5) ;  and

n = (int) Math.round(x)

For what values of x do they give the same result? For what values of x do they give different results?

2.      What is a final variable? Can you define a final variable without supplying its value (without initializing it with the declaration)?  Try it!

3.      What are the values of the following expressions.  In each line assume that:

double x = 2.5;

double y = -1.5;

int m = 18, n = 4;

a.)              x + n * y – (x + n) * y

b.)             m / n + m % n

c.)              5 * x – n / 5

d.)             Math.sqrt(Math.sqrt(n))

e.)              (int) Math.round(x)

f.)               (int) Math.round(x) + (int) Math.round(y)

 

4.      Copy the CashRegister Class files found in J:\CS210 and Compile and Run program.  Enhance the CashRegister class so that it keeps track of the total number of items in a sale.  Count all recorded purchases an supply a method:

int getItemCount()

that returns the number of items of the current purchase.  Remenber to reset the counter at the end of the purchase.

 

  1. Write a program that prompts the user for two numbers, then prints

To do this implement a class:

publin class Pair

{

public Pair (double aFirst, double aSecond) { … }

 

public double getSum() { . . .}

Implement a class PairTest that reads in two numbers, constructs a Pair object, invokes its methods, and prints the results.

6.      Open the Horstmann: Big Java, 2 e - Student Companion Site.Go to the Labs link and open Labs 6 & 7 as revision of Decision (if-else) and Iteration (for, while etc.,).  Study all questions and answer Lab 6 question 14 in particular. In Lab 7 answer questions 8, 9, and 10.    

7.      Write a program that reads a sequence of integers into and array and that computes the alternating sum of all elements in the array.  For example, if the program is executed with the input data:

1 4 9 16 9 7 4 9 11

then it computes

1 - 4 + 9 - 16 + 9 - 7 + 4 - 9 + 11 = -2;

 

If the the number of  integers read exceeds the initial size of the array then the array should be copied to a new array which is twice the length of the initial array.  You can use the static System.arraycopy method to copy an array and store the reference to the new array in the old array reference.

System.arraycopy(array1, startposition_array1 , array2, startposition_array2, array1.length);

array2=array1;