Big Java Early Object Chapter 7 Review Exercise – Array and ArrayList – Cay S. Horstmann – Part – 2

Big Java Early Object Chapter 7 Review Exercise – Array and ArrayList – Cay S. Horstmann – Part – 2

  1. Carry out the following tasks with an array:
  1. Allocate an array a of ten integers.
  2. Put the number 17 as the initial element of the array.
  3. Put the number 29 as the last element of the array.
  4. Fill the remaining elements with –1.
  5. Add 1 to each element of the array.
  6. Print all elements of the array, one per line.
  7. Print all elements of the array in a single line, separated by commas.

Ans:

1. int []arr = new int[10];

2. arr[0] = 17;

3. arr[9] = 29;

4. for(i=1;i<9;i++){

                             arr[i]= -1;

                      }

5. for(i=;i<10;i++){

                             arr[i]++;

                      }

6. for(i=;i<10;i++){

                             System.out.println(arr[i]);

                      }

7. for(i=;i<10;i++){

                             System.out.print(arr[i]);

                             if(i<9)System.out.print(“,”);

                      }

 

  1. What is an index of an array? What are the legal index values? What is a

bounds error?

Ans: Index is location of  an element in an array. The legal index values are from 0 to size-1. If we try to access an indexed element which doesn’t exist in the array or which is not legal then the error is called bounds error.

  1. Write a program that contains a bounds error. Run the program. What happens on your computer?

Ans: int arr[3] = {2,3,4}

          System.out.println(arr[3]);

It shows IndexOutOfBoundsException.

 

  1. Write a loop that reads ten numbers and a second loop that displays them in the

opposite order from which they were entered.

Ans: for(i=0;i<10;i++){

                   arr[i] = in.nextInt();

          }

          for(i;i>=0;i–){

                   System.out.println(arr[i]);

          }

  1. Write code that fills an array values with each set of numbers below.
    1. 1 2 3 4 5 6 7 8 9 10
    2. 0 2 4 6 8 10 12 14 16 18 20
    3. 1 4 9 16 25 36 49 64 81 100
    4. 0 0 0 0 0 0 0 0 0 0
    5. 1 4 9 16 9 7 4 9 11
    6. 0 1 0 1 0 1 0 1 0 1
    7. 0 1 2 3 4 0 1 2 3 4

Ans:

1. for(i=0;i<10;i++){

                   arr[i]=i+1;

          }

2. for(i=0;i<=10;i++){

                   arr[i]=i*2;

          }

3. for(i=0,j=1;i<10;i++){

                   if(i==0)arr[i]=j;

4. else arr[i]=arr[i-1]+j;

                   j=j+2;

          }

5. for(i=0;i<10;i++){

                   arr[i] = 0;

          }

6. arr[]={1,4,9,16,9,7,4,9,11};

7. for(i=0;i<10;i++){

                   arr[i]=i%2;

          }

8. for(i=0;i<5;i++){

                   arr[i]=i;

                   arr[i+5]=i;

          }

 

  1. Consider the following array:

int[] a = { 1, 2, 3, 4, 5, 4, 3, 2, 1, 0 };

What is the value of total after the following loops complete?

  1. int total = 0;

for (int i = 0; i < 10; i++) { total = total + a[i]; }

  1. int total = 0;

for (int i = 0; i < 10; i = i + 2) { total = total + a[i]; }

  1. int total = 0;

for (int i = 1; i < 10; i = i + 2) { total = total + a[i]; }

  1. int total = 0;

for (int i = 2; i < 10; i++) { total = total + a[i]; }

  1. int total = 0;

for (int i = 1; i = 0; i–) { total = total + a[i]; }

  1. int total = 0;

for (int i = 9; i >= 0; i = i – 2) { total = total + a[i]; }

  1. int total = 0;

for (int i = 0; i < 10; i++) { total = a[i] – total; }

Ans:

1. 25

2. 13

3. 12

4. 22

5. 11

6. 25

7. 12

8. -1

  1. Consider the following array:

int[] a = { 1, 2, 3, 4, 5, 4, 3, 2, 1, 0 };

What are the contents of the array a after the following loops complete?

  1. for (int i = 1; i < 10; i++) { a[i] = a[i – 1]; }
  2. for (int i = 9; i > 0; i–) { a[i] = a[i – 1]; }
  3. for (int i = 0; i < 9; i++) { a[i] = a[i + 1]; }
  4. for (int i = 8; i >= 0; i–) { a[i] = a[i + 1]; }
  5. for (int i = 1; i < 10; i++) { a[i] = a[i] + a[i – 1]; }
  6. for (int i = 1; i < 10; i = i + 2) { a[i] = 0; }
  7. for (int i = 0; i < 5; i++) { a[i + 5] = a[i]; }
  8. for (int i = 1; i < 5; i++) { a[i] = a[9 – i]; }

Ans:

  1. {1,1,1,1,1,1,1,1,1,1}
  2. {1,1,2,3,4,5,4,3,2,1}
  3. {2,3,4,5,4,3,2,1,0,0}
  4. {0,0,0,0,0,0,0,0,0,0}
  5. {1,3,6,10,15,19,22,24,25,25}
  6. {1,0,3,0,5,0,3,0,1,0}
  7. {1,2,3,4,5,1,2,3,4,5}
  8. {1,1,2,3,4,4,3,2,1,0}
  1. Write a loop that fills an array values with ten random numbers between 1 and 100.

Write code for two nested loops that fill values with ten different random numbers

between 1 and 100.

Ans:

This fills the arra with ten random numbers:

private int Random[];

private int k=0;

for(i=1;i<=2;i++){

for(j=1;j<=5;j++){

Random[k] = (Math.random()*((100-1)+1))+1;

k++;

}

}

 

This fills the array with ten different random values:

int[] a = new int[10];

Random generator = new Random();

int[] values = new int[100];

for (int i = 0; i < 100; i++)   values[i] = i + 1; 

for (int i = 0; i < 10; i++){

int r = generator.nextInt(100 – i);

a[i] = values[r];

values[r] = values[100 – i – 1];

}

 

  1. Write Java code for a loop that simultaneously computes both the maximum and

minimum of an array.

Ans:

private int values[];

Arrays.sort(values);

private int maximum = values[values.size-1];

private int minimum = values[0];

  1. What is wrong with each of the following code segments?
    1. int[] values = new int[10];

for (int i = 1; i <= 10; i++){

values[i] = i * i;

}

2. int[] values;

for (int i = 0; i < values.length; i++){

values[i] = i * i;

}

Ans:

1. IndexOutOfBounds Exception

Here we skipped first index but we tried to access values of index 10 which doesn’t exists.

2. For loop will not work.

The size of an array not initialized is 0. Hence the for loop doesn’t work.

 

  1. Write enhanced for loops for the following tasks.
    1. Printing all elements of an array in a single row, separated by spaces.
    2. Computing the maximum of all elements in an array.
    3. Counting how many elements in an array are negative.

Ans:

1. int i=0;

for(double element:values){

          if(i!=0)System.out.print(“ ”);

                   System.out.print(element);

                   i++;

}

2. double maximum;

int i=0;

for(double element:values){

if(i==0){

maximum=element;

i++;

}

          if(maximum<element)swap(maximum=element);

}

3. int count=0;

for(double element:values){

          if(element<0)count++;

}

  1. Rewrite the following loops without using the enhanced for loop construct. Here, values is an array of floating-point numbers.
    1. for (double x : values) { total = total + x; }
    2. for (double x : values) { if (x == target) { return true; } }
    3. int i = 0;

for (double x : values) { values[i] = 2 * x; i++; }

Ans:

1. for(i=0;i<values.size;i++){

total=total+values[i];

}

2. for(i=0;i<values.size;i++){

if (values[i] == target) { return true; }

}

3. for(i=0;i<values.size;i++){

values[i]=values[i]*2;

}

  1. Rewrite the following loops using the enhanced for loop construct. Here, values is an

array of floating-point numbers.

  1. for (int i = 0; i < values.length; i++) { total = total + values[i]; }
  2. for (int i = 1; i < values.length; i++) { total = total + values[i]; }
  3. for (int i = 0; i < values.length; i++){if (values[i] == target) { return i; }}

Ans:

1. for (double x : values) { total = total + x; }

2. int i=0;

for (double x : values) {

total = total + x;

if(i==0)total=total-x;

i++;

}

3. int i=0;

for (double x : values) {

if (x == target) { return i; }

i++;

}

  1. What is wrong with each of the following code segments?
    1. ArrayList values = new ArrayList();
    2. ArrayList values = new ArrayList();
    3. ArrayList values = new ArrayList;
    4. ArrayList values = new ArrayList();

for (int i = 1; i <= 10; i++)

{

values.set(i – 1, i * i);

}

5. ArrayList values;

for (int i = 1; i <= 10; i++)

{

values.add(i * i);

}

Ans:

1. ArrayList is generic class type data.

          ArrayList values = new ArrayList();

2. There should be name of generic class after ArrayList.

          ArrayList values = new ArrayList();

3. There should be parenthesis before ‘;’.

          ArrayList values = new ArrayList();

4. Values should be added before set.

ArrayList values = new ArrayList();

for (int i = 1; i <= 10; i++)values.add(i – 1, i * i);

5. ArrayList declaration is not completed.

ArrayList values = new ArrayList();

for (int i = 1; i <= 10; i++)values.add(i * i);

  1. For the operations on partially filled arrays below, provide the header of a method. Do not implement the methods.
    1. Sort the elements in decreasing order.
    2. Print all elements, separated by a given string.
    3. Count how many elements are less than a given value.
    4. Remove all elements that are less than a given value.
    5. Place all elements that are less than a given value in another array.

Ans:

1. void decendingSort(int []values){

          }

2. void decendingSort(int []values, String saperator){

          }

3. void decendingSort(int []values, int value){

          }

4. void decendingSort(int []values, int value){

          }

5. void decendingSort(int []values, int value){

          }

  1. Trace the flow of the given loop with the given array. Show two columns, one with the value of i and one with the output.

Loop:

for (int i = 0; i 0)System.out.print(” | “);

System.out.print(values[i]);

}

Array: 32 | 54 | 67.5 | 29 | 35

Ans:

i=0    values[i]=32

i=1    values[i]=54

i=2    values[i]=67.5

i=3    values[i]=29

i=4    values[i]=35

  1. Consider the following loop for collecting all elements that match a condition; in this case, that the element is larger than 100.

ArrayList matches = new ArrayList();

for (double element : values){

if (element > 100)matches.add(element);

}

Trace the flow of the loop, where values contains the elements 110, 90, 100, 120, 80. Show two columns, for element and matches.

Ans:

element=110        matches={110}

element=90          matches={110}

element=100        matches={110}

element=120        matches={110,120}

element=80          matches={110,120}

  1. Trace the flow of the loop below, where values contains the elements 80, 90, 100, 120, 110. Show two columns, for pos and found. Repeat the trace when values contains the elements 80, 90, 120, 70.

Loop:

int searchedValue = 100;

int pos = 0;

boolean found = false;

while (pos < values.length && !found){

if (values[pos] == searchedValue)found = true;

else  pos++;

}

if (found) { System.out.println(“Found at position: ” + pos); }

else { System.out.println(“Not found”); }

Ans:

pos=0                   found=false

pos=1                   found=false

pos=2                   found=true

Repeatation:

pos=0                   found=false

pos=1                   found=false

pos=2                   found=false

pos=3                   found=false

  1. Trace the algorithm for removing an element given below. Use an array values with elements 110, 90, 100, 120, 80, and remove the element at index 2.

Algorithm:

values[pos] = values[currentSize – 1];

currentSize–;

Ans:

values[2]=80

currentsize=4

values={110,90,80,120}

  1. Give pseudocode for an algorithm that rotates the elements of an array by one position, moving the initial element to the end of the array.

Ans:

get the array

keep first value in temp

for start to end-1

set values of next index at current index

set temp to end

  1. Give pseudocode for an algorithm that removes all negative values from an array, preserving the order of the remaining elements.

Ans:

get the array

for start to  end

if value is negative do

          for pos to end

                   move value to lower index

          end=end-1

  1. Suppose values is a sorted array of integers. Give pseudocode that describes how a new value can be inserted so that the resulting array stays sorted.

Ans:

get the array

get the item

for start to  end

if value is matched do

          for end to pos

                   move value to upper index

          set the item at position pos

  1. A run is a sequence of adjacent repeated values. Give pseudocode for computing the length of the longest run in an array. For example, the longest run in the array with elements

1 2 5 5 3 1 2 4 3 2 2 2 2 3 6 5 5 6 3 1

has length 4.

Ans:

get the array

set count=1

for start to end

          if repeated

count++

          if not repeated

longest=count

count=1

  1. What is wrong with the following method that aims to fill an array with random numbers?

public void makeCombination(int[] values, int n){

Random generator = new Random();

int[] numbers = new int[values.length];

for (int i = 0; i < numbers.length; i++){

numbers[i] = generator.nextInt(n);

}

values = numbers;

}

Ans: You cannot assign an array to another array directly.

It should be copied:

values= Arrays.copyOf(numbers,numbers.length);

  1. You are given two arrays denoting x– and y-coordinates of a set of points in a plane. For plotting the point set, we need to know the x– and y-coordinates of the smallest rectangle containing the points. How can you obtain these values from the fundamental algorithms below?

Algorithm:

for (int i = 0; i < values.length; i++){

values[i] = i * i;

}

Ans: Assigning values[i]=x[i]*y[i] we can obtain the rectangle, then we can find coordinates.As:

for (int i = 0; i < values.length; i++){

values[i] = x[i] * y[i];

}

  1. Solve the quiz score problem described below by sorting the array first. How do you need to modify the algorithm for computing the total?

Problem: You are given the quiz scores of a student. You are to compute the final quiz score, which is the sum of all scores after dropping the lowest one. For example, if the scores are:  8, 7, 8.5, 9.5, 7, 4, 10

Ans:

double smallest = values[0];

double total=0;

for (int i = 1; i < values.length; i++){

if (values[i] < smallest){

smallest = values[i];

smallestPosition = i;

}

}

values[smallestPosition]=values[values.length-1];

for(i=0;i<values.length-1;i++)total=total+values[i];

27. Solve the task described below using an algorithm that removes and inserts elements instead of switching them. Write the pseudocode for the algorithm, assuming that methods for removal and insertion exist. Act out the algorithm with a sequence of coins and explain why it is less efficient than the swapping algorithm given below.

Problem:

You are given an array whose size is an even number, and you are to switch the

first and the second half. For example, if the array contains the eight numbers

9 13 21 4 11 7 1 3

then you should change it to

11 7 1 3 9 13 21 4

Algorithm:

i = 0

j = … (we’ll think about that in a minute)

While (don’t know yet)

Swap elements at positions i and j

i++

j++

Ans:

Algorithm:

for(i=0,j=5;i<5;i++,j++){

          temp=values[i];

          values[i]=values[j];

values[j]=temp;

}

Pseudocode:

j=5

for i=0 to 4

          remove values[i]

          insert values[i]

          remove values[j]

remove values[j]

j++

Implementation:

{9, 13, 21, 4, 11, 7, 1, 3}

{13, 21, 4, 11, 7, 1, 3}

{11, 13, 21, 4, 7, 1, 3}

{11, 13, 21, 4, 9, 7, 1, 3}

{11, 21, 4, 9, 7, 1, 3}

{11, 7, 21, 4, 9, 1, 3}

{11, 7, 21, 4, 9, 13, 1, 3}

{11, 7, 4, 9, 13, 1, 3}

{11, 7, 1, 4, 9, 13, 3}

{11, 7, 1, 4, 9, 13, 21, 3}

{11, 7, 1, 9, 13, 21, 3}

{11, 7, 1, 3, 9, 13, 21}

{11, 7, 1, 3, 9, 13, 21, 4}

It is less efficient than swapping because it needs much steps and much executing time.

  1. Develop an algorithm for finding the most frequently occurring value in an array of numbers. Use a sequence of coins of values 2,4, 3,3, 5,7,4,3. Place paper clips below each coin that count how many other coins of the same value are in the sequence. Give the pseudocode for an algorithm that yields the correct answer, and describe how using the coins and paper clips helped you find the algorithm.

Ans:

Algorithm:

for i=1 to values.length-1

          if (values[i]==values[i-1])frequent[values[i]]=1

Number of  Coins in Paper Clip:

2        1

4        2

3        3

5        1

7        1

Pseudoode:

for start to end

          if(item is not counted)

                   count the number of similar items

Using the paper clip and coins we can trace how the operation is being occurred and we can be helped to develop algorithm.

 

  1. Write Java statements for performing the following tasks with an array declared as

int[][] values = new int[ROWS][COLUMNS];

  1. Fill all entries with 0.
  2. Fill elements alternately with 0s and 1s in a checkerboard pattern.
  3. Fill only the elements in the top and bottom rows with zeroes.
  4. Compute the sum of all elements.
  5. Print the array in tabular form.

Ans:

1. for(i=0;i<ROWS;i++){

                   for(j=0;j<COLUMNS;j++)values[i][j]=0;

}

2. for(i=0;i<ROWS;i++){

                   for(j=0;j<COLUMNS;j++)values[i][j]=(i+j)%2;

}

3. for(i=0;i<ROWS;i++){

                   if(i==0||i==ROWS-1)for(j=0;j<COLUMNS;j++)values[i][j]=0;

}

4. for(i=0;i<ROWS;i++){

                   for(j=0;j<COLUMNS;j++)sum=sum+values[i][j];

}

5. for(i=0;i<ROWS;i++){

                   for(j=0;j<COLUMNS;j++)System.out.print(values[i][j]);

                   System.out.println();

}

  1. Write pseudocode for an algorithm that fills the first and last columns as well as the first and last rows of a two-dimensional array of integers with –1.

Ans:

Pseudocode-1:

for i=0 to columnnumber-1

          if i==0 or i==columnnumber-1

for j=0 to rownumber-1

          values[j][i]=-1

 

Pseudocode-2:

for i=0 to rownumber-1

          if i==0 or i==rownumber-1

for j=0 to columnnumber-1

          values[i][j]=-1

  1. You must be careful about updating the index value when you remove elements from an array list. Show how you can avoid this problem by traversing the array list backwards.

Ans: We can avoid this problem by shifting every value from right to the removed value and decreasing the size.

  1. True or false?
    1. All elements of an array are of the same type.
    2. Arrays cannot contain strings as elements.
    3. Two-dimensional arrays always have the same number of rows and columns.
    4. Elements of different columns in a two-dimensional array can have different types.
    5. A method cannot return a two-dimensional array.
    6. A method cannot change the length of an array argument.
    7. A method cannot change the number of columns of an argument that is a two-dimensional array.

Ans:

1.True

2.False

3.False

4.False

5.False

6. True

7.True

  1. How do you perform the following tasks with array lists in Java?
    1. Test that two array lists contain the same elements in the same order.
    2. Copy one array list to another.
    3. Fill an array list with zeroes, overwriting all elements in it.
    4. Remove all elements from an array list.

Ans:

1. boolean result = Arrays.equals(listOne.toArray(),listTwo.toArray());

2. ArrayList myObject = new ArrayList(myTempObject);

3. i=0;

while(hasIntNext){

if(i<list.size)list.set(i, values[i];

                   else  list.add(i, values[i]);

                   i++;

}

4. list.clear();

  1. True or false?
    1. All elements of an array list are of the same type.
    2. Array list index values must be integers.
    3. Array lists cannot contain strings as elements.
    4. Array lists can change their size, getting larger or smaller.
    5. A method cannot return an array list.
    6. A method cannot change the size of an array list argument.

Ans:

  1. True
  2. True
  3. False
  4. True
  5. False
  6. True

Download As PDF

Leave a Reply

Your email address will not be published. Required fields are marked *