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

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

  1. Declare an array of integers containing the first five prime numbers.

Ans: int primes[] = {2,3,5,7,11}

 

  1. Assume the array primes has been initialized as described in Self Check 1. What does it contain after executing the following loop?

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

primes[4 – i] = primes[i];

}

Ans:  primes[0] = 2

          Primes[1] = 3

          Primes[2] = 5

   Primes[3] = 3

          Primes[4] = 2

 

  1. Assume the array primes has been initialized as described in Self Check 1. What

does it contain after executing the following loop?

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

primes[i]++;

}

Ans:  primes[0] = 3

          Primes[1] = 4

          Primes[2] = 6

   Primes[3] = 8

          Primes[4] = 12

 

  1. Given the declaration

int[] values = new int[10];

write statements to put the integer 10 into the elements of the array values with

the lowest and the highest valid index.

Ans:  values[0] = 10;

          values[9] = 10;         

 

  1. Declare an array called words that can hold ten elements of type String.

Ans:  String []words = new String[10];

  1. Declare an array containing two strings, “Yes”, and “No”.

Ans:  String []words = {“Yes”, “No”};

 

  1. Can you produce the output below without storing the inputs in an array,

by using an algorithm below for finding the maximum ?

Output:

32

54

67.5

29

35

80

115 <= largest value

44.5

100

65

Algorithm:

double largest = in.nextDouble();

while (in.hasNextDouble()){

double input = in.nextDouble();

if (input > largest)largest = input;

}

Ans: No. Because you don’t store the values, you need to print them when you read them. But you don’t know where to add the <= until you have seen all values.

  1. Declare a method of a class Lottery that returns a combination of n numbers. You don’t need to implement the method.

Ans:

Public class Lottery{

          public int[] arrayReturn(){

                    ……

}

}

 

  1. What does this enhanced for loop do?

int counter = 0;

for (double element : values){

if (element == 0) { counter++; }

}

Ans: Assign items in ‘values’ to ‘element’ one by one and check how much of them are equal to 0.

  1. Write an enhanced for loop that prints all elements in the array values.

Ans:

for (double element : values){

          System.out.println(element);

}

  1. Write an enhanced for loop that multiplies all elements in a double[] array named factors, accumulating the result in a variable named product.

Ans:

private double product = 1.0;

for (double element : factors){

          product =product * element;

}

  1. Why is the enhanced for loop not an appropriate shortcut for the following basic for loop?

for (int i = 0; i < values.length; i++) { values[i] = i * i; }

Ans: Because the enhanced for loop does not have the index variable i.

  1. Given these inputs, what is the output of the LargestInArray program?

20 10 20 Q

Ans: 20, 20.

  1. Write a loop that counts how many elements in an array are equal to zero.

Ans:

int counter = 0;

for (double element : values){

if (element == 0) counter++;

}

  1. Consider the algorithm to find the largest element in an array. Why don’t we

initialize largest and i with zero, like this?

double largest = 0;

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

if (values[i] > largest)largest = values[i];

}

Ans: Because if all elements in the array are negative than the program will give wrong output 0.

  1. When printing separators, we skipped the separator before the initial element.

Rewrite the loop so that the separator is printed after each element, except for

the last element.

Ans:

if(values.length>0)System.out.print(values[0]);

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

System.out.print(“, ” + values[i]);

}

  1. What is wrong with these statements for printing an array with separators?

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

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

System.out.print(“, ” + values[i]);

}

Ans: Because, if there is no element in the array than it will throw an Exeption.

  1. When finding the position of a match, we used a while loop, not a for loop. What is wrong with using this loop instead?

for (pos = 0; pos < values.length && !found; pos++){

if (values[pos] > 100)found = true;

}

Ans: Because, After finishing for loop the value of ‘pos’ is 1 increased than real value and give wrong output.

  1. When inserting an element into an array, we moved the elements with larger

index values, starting at the end of the array. Why is it wrong to start at the insertion  location, like this?

for (int i = pos; i < currentSize – 1; i++){

values[i + 1] = values[i];

}

Ans: Because if we do so, after finishing the operation all elements in the array become same as it assign all elements to value[pos].

  1. Below has two algorithms for removing an element. Which of the two

should be used to remove 4 from the given array.?

Algorithm-1:

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

currentSize–;

Algorithm-2:

for (int i = pos + 1; i < currentSize; i++){

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

}

currentSize–;

Array: 8, 7, 8.5, 9.5, 7, 4, 10

Ans: Algorithm-1 should be used. Because this array is not sorted.

  1. It isn’t actually necessary to remove the minimum in order to compute the total

score. Describe an alternative.

Ans: We can find the total except lowest one without removing minimum from the array. We can sort the array in ascending order then skipping first element we can find the sum. Show the fragment below:

int sum=0;

Arrays.sort(values);

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

sum = sum + values[i];

}        

or,

Find the minimum value.

Calculate the sum.

Subtract the minimum value.

  1. How can you print the number of positive and negative values in a given array?

Ans: By comparing each value with 0 whether it is greater or less than 0. See the fragment below:

int pos = 0;

          int neg = 0;

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

                    if(values[i]>0)pos++;

                   if(values[i]<0)neg++;

}

System.out.println(pos);

System.out.println(neg);

  1. How can you print all positive values in an array, separated by commas?

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

                    if(values[i]>0){

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

                             if(i<values.length-1)System.out.println(“,”);

                   }

}

  1. Consider the following algorithm for collecting all matches in an array:

int matchesSize = 0;

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

if (values[i] fulfills the condition){

matches[matchesSize] = values[i];

matchesSize++;

}

}

How can this algorithm help you to print all positive values in an array, separated by commas?

Ans: We can find all positive values in the array and save them in a new array by the algorithm. Then we can directly print them separated by comma.

  1. Walk through the algorithm below, using two paper clips to indicate the positions for i and j. Explain why there are no bounds errors in the pseudocode.

Algorithm:

i = 0

j = size/2

While (I<size/2)

Swap elements at positions i and j

i++

j++

Ans: Here value of i is from 0 to size/2-1 and value of j is from size/2 to size if size is an even number. But if size is odd the value of j is from size/2 ro size-1. The last element remain behind the operation. So there are no bounds errors in the pseudocode.

  1. Take out some coins and simulate the following pseudocode, using two paper

clips to indicate the positions for i and j.

i = 0

j = size – 1

While (i < j)

Swap elements at positions i and j

i++

j–

What does the algorithm do?

Ans: It reverses the elements in the array.

  1. Consider the task of rearranging all elements in an array so that the even numbers come first. Otherwise, the order doesn’t matter. For example, the array

1 4 14 2 1 3 5 6 23

could be rearranged to

4 2 14 6 1 5 3 23 1

Using coins and paperclips, discover an algorithm that solves this task by

swapping elements, then describe it in pseudocode.

Ans: Here is one solution. The basic idea is to move all odd elements to the end. Put one paper clip at the beginning of the array and one at the end. If the element at the first paper clip is odd, swap it with the one at the other paper clip and move that paper clip to the left. Otherwise, move the first paper clip to the right. Stop when the two paper clips meet. Here is the pseudocode:

i = 0

j = size – 1

while (i < j)

if (a[i] is odd)

swap elements at positions i and j.

j–

else

i++

  1. 28. Discover an algorithm for removal and insertion of elements instead of swapping.

Ans:

Here is one solution. The idea is to remove all odd elements and move them to the end. The trick is to know when to stop. Nothing is gained by moving odd elements into the area that already contains moved elements, so we want to mark that area with another paper clip.

i = 0

moved = size

While (i < moved)

If (a[i] is odd)

Remove the element at position i and add it at the end.

moved–

  1. Consider the algorithm that finds the largest element in a sequence of inputs, not the largest element in an array. Why is this algorithm better visualized by picking playing cards from a deck rather than arranging toy soldiers in a sequence?

Ans: When you read inputs, you get to see values one at a time, and you can’t peek ahead. Picking cards one at a time from a deck of cards simulates this process better than looking at a sequence of items, all of which are revealed.

playing_cards_deck.png

  1. What results do you get if you total the columns in our sample medals data?

Ans: Total: 5  5  5  15

 

  1. Consider an 8 × 8 array for a board game:

int[][] board = new int[8][8];

Using two nested loops, initialize the board so that zeroes and ones alternate, as on a checkerboard:

0 1 0 1 0 1 0 1

1 0 1 0 1 0 1 0

0 1 0 1 0 1 0 1

. . .

1 0 1 0 1 0 1 0

Ans:

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

          for(j=0;j<8;j++){

                    board[i][j]=(i+j)%2;

}

}

  1. Declare a two-dimensional array for representing a tic-tac-toe board. The board has three rows and columns and contains strings “x”, “o”, and ” “.

Ans: String[][] str = new String[3][3];

 

  1. Write an assignment statement to place an “x” in the upper-right corner of the

tic-tac-toe board.

Ans: str[0][2] = “x”;

 

  1. Which elements are on the diagonal joining the upper-left and the lower-right

corners of the tic-tac-toe board?

Ans: str[0][0], str[1][1], str[2][2].

  1. Declare an array list of integers called primes that contains the first five prime

numbers (2, 3, 5, 7, and 11).

Ans:  ArrayList primes = new ArrayList();

            primes.add(2);

            primes.add(3);

            primes.add(5);

    primes.add(7);

            primes.add(11);

  1. Given the array list primes containing integers (2,3,5,7,11), write a loop to print its elements in reverse order, starting with the last element.

Ans:

for (int i = primes.size()-1; i >=0; i–){

int prime = primees.get(i);

System.out.println(prime);

}

 

  1. What does the array list names contain after the following statements?

ArrayList names = new ArrayList;

names.add(“Bob”);

names.add(0, “Ann”);

names.remove(1);

names.add(“Cal”);

Ans: [“Ann”, “Cal”]

Steps:[“Bob”]

          [“Ann”, “Bob”]

          [“Ann”]

          [“Ann”, “Cal”]

  1. What is wrong with this code snippet?

ArrayList names;

names.add(Bob);

Ans: Error—names not initialized.

 

  1. Consider this method that appends the elements of one array list to another:

public void append(ArrayList target, ArrayList source){

for (int i = 0; i < source.size(); i++){

target.add(source.get(i));

}

}

What are the contents of names1 and names2 after these statements?

ArrayList names1 = new ArrayList();

names1.add(“Emily”);

names1.add(“Bob”);

names1.add(“Cindy”);

ArrayList names2 = new ArrayList();

names2.add(“Dave”);

append(names1, names2);

Ans:

names1 = [“Emily”, “Bob”, “Cindy”, “Dave”]

names2 = [“Dave”]

  1. Suppose you want to store the names of the weekdays. Should you use an array

list or an array of seven strings?

Ans: Array. Because the number of weekdays doesn’t  change, there is no disadvantage to using an array, and it is easier to initialize:

String[] weekdayNames = { “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday” };

Download As PDF

Leave a Reply

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