Bedford-computing.co.uk
Chapter 6 Programming Exercise Solutions
P6.1
public class ArrayPrinter
{
public static void main(String[] args)
{
int[] data = new int[10];
for (int i = 0; i < 10; i++)
{
data[i] = (int) (Math.random() * 100 + 1);
}
// Print out even indices
for (int i = 0; i < data.length; i = i + 2)
{
System.out.print(data[i] + " ");
}
System.out.println();
// Print out even elements
for (int i = 0; i < data.length; i++)
{
if (data[i] % 2 == 0)
{
System.out.print(data[i] + " ");
}
}
System.out.println();
// Print out elements in reverse order
for (int i = data.length - 1; i >= 0; i--)
{
System.out.print(data[i] + " ");
}
System.out.println();
// Print out only first and last element
System.out.printf("%d %d\n", data[0], data[data.length - 1]);
}
}
P6.2
Array methods that do the following:
a) Swap first and last elements in an array.
public static void swapFirstLast(int[] arr)
{
int last = arr.length - 1;
int temp = arr[0];
arr[0] = arr[last];
arr[last] = temp;
}
public static void main(String[] args)
{
int[] randoms = new int[10];
// Create a test array containing random numbers.
for (int i = 0; i < 10; i++)
{
randoms[i] = (int) (Math.random() * 100) + 1;
// Print the values as they are assigned.
System.out.print(randoms[i] + " ");
}
System.out.println();
// Perform the swap.
swapFirstLast(randoms);
// Print again to see new order.
for (int i = 0; i < 10; i++)
{
System.out.print(randoms[i] + " ");
}
System.out.println();
}
b) Shift all elements by one to the right.
public static void rotateRight(int[] arr)
{
int last = arr.length - 1;
int temp = arr[last];
for (int i = last; i > 0; i--)
{
arr[i] = arr[i - 1];
}
arr[0] = temp;
}
public static void main(String[] args)
{
int[] randoms = new int[10];
// Create a test array containing random numbers.
for (int i = 0; i < 10; i++)
{
randoms[i] = (int) (Math.random() * 100) + 1;
// Print the values as they are assigned.
System.out.print(randoms[i] + " ");
}
System.out.println();
// Rotate the array once to the right.
rotateRight(randoms);
// Print again to see new order.
for (int i = 0; i < 10; i++)
{
System.out.println(randoms[i] + " " );
}
System.out.println();
}
c) Replace all even elements with 0.
public static void replaceEven(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) // Number is even
{
arr[i] = 0;
}
}
}
public static void main(String[] args)
{
int[] randoms = new int[10];
// Create a test array containing random numbers.
for (int i = 0; i < 10; i++)
{
randoms[i] = (int) (Math.random() * 100) + 1;
// Print the values as they are assigned.
System.out.print(randoms[i] + " ");
}
System.out.println();
// Replace the even elements.
replaceEven(randoms);
// Print again to see new elements.
for (int i = 0; i < 10; i++)
{
System.out.print(randoms[i] + " ");
}
System.out.println();
}
d) Replace each element except first and last by the larger of its two neighbors.
public static void replaceWithLargestNeighbor(int[] arr)
{
// Start loop at one, and stop before the end
for (int i = 1; i < arr.length - 1; i++)
{
if (arr[i - 1] > arr[i + 1])
{
arr[i] = arr[i - 1];
}
else
{
arr[i] = arr[i + 1];
}
}
}
public static void main(String[] args)
{
int[] randoms = new int[10];
// Create a test array containing random numbers.
for (int i = 0; i < 10; i++)
{
randoms[i] = (int) (Math.random() * 100) + 1;
// Print the values as they are assigned.
System.out.print(randoms[i] + " ");
}
System.out.println();
// Replace with largest neighbor
replaceWithLargestNeighbor(randoms);
// Print again to see new elements.
for (int i = 0; i < 10; i++)
{
System.out.print(randoms[i] + " ");
}
System.out.println();
}
e) Remove the middle element if the array length is odd, or middle two if even.
public static void removeMiddle(int[] arr)
{
int size = arr.length;
if (size % 2 == 0) // Size is even
{
// Figure out starting point for removal
int firstToRemove = size / 2 - 1;
// Remove middle two elements
for (int i = firstToRemove; i < size - 2; i++)
{
arr[i] = arr[i + 2];
}
}
else // Size is odd
{
// Figure out starting point for removal
int firstToRemove = size / 2;
// Remove middle element
for (int i = firstToRemove; i < size - 1; i++)
{
arr[i] = arr[i + 1];
}
}
}
public static void main(String[] args)
{
int[] randoms = new int[11];
// Create a test array containing random numbers
for (int i = 0; i < randoms.length; i++)
{
randoms[i] = (int) (Math.random() * 100) + 1;
// Print the values as they are assigned.
System.out.print(randoms[i] + " " );
}
System.out.println();
// Remove the middle element(s)
removeMiddle(randoms);
// Print again to see new order.
for (int i = 0; i < randoms.length; i++)
{
System.out.print(randoms[i] + " ");
}
System.out.println();
randoms = new int[10];
// Create a test array with an even number of elements
for (int i = 0; i < randoms.length; i++)
{
randoms[i] = (int) (Math.random() * 100) + 1;
// Print the values as they are assigned.
System.out.print(randoms[i] + " " );
}
System.out.println();
// Remove the middle element(s)
removeMiddle(randoms);
// Print again to see new order.
for (int i = 0; i < randoms.length; i++)
{
System.out.print(randoms[i] + " ");
}
System.out.println();
}
f) Move all even elements to the front, otherwise preserving order
public static void moveEvenToFront(int[] arr)
{
int endOfEvens = 0;
int temp;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) // Even
{
temp = arr[i]; // Save the even number
// Move array element from end of
// evens to current location
for (int j = i; j > endOfEvens; j--)
{
arr[j] = arr[j - 1];
}
arr[endOfEvens] = temp;
endOfEvens++;
}
}
}
public static void main(String[] args)
{
int[] randoms = new int[10];
// Create a test array containing random numbers.
for (int i = 0; i < randoms.length; i++)
{
randoms[i] = (int) (Math.random() * 100) + 1;
// Print the values as they are assigned.
System.out.print(randoms[i] + " " );
}
System.out.println();
// Move the evens to the front.
moveEvenToFront(randoms);
// Print again to see new order.
for (int i = 0; i < randoms.length; i++)
{
System.out.print(randoms[i] + " " );
}
System.out.println();
}
g) Return second-largest element in array.
public static int getSecondLargest(int[] arr)
{
// One way to do it: Find maximum once.
int max = arr[0];
for (int i = 1; i < size; i++)
{
if (arr[i] > max)
{
max = arr[i];
}
}
// 2. Find the max again, ignoring the real max.
int oldMax = max;
max = arr[0];
for (int i = 1; i < size; i++)
{
if (arr[i] != oldMax)
{
if (arr[i] > max)
{
max = arr[i];
}
}
}
return max;
}
public static void main(String[] args)
{
int[] randoms = new int[10];
// Create a test array containing random numbers.
for (int i = 0; i < randoms.length; i++)
{
randoms[i] = (int) (Math.random() * 100) + 1;
// Print the values as they are assigned.
System.out.print(randoms[i] + " " );
}
System.out.println();
// Find the second largest.
System.out.println("The second largest number is " +
+ getSecondLargest(randoms));
}
h) Return true if array is currently in increasing order.
public static boolean inOrder(int[] arr)
{
// Assume they are in order.
boolean ordered = true;
// Loop through array, checking for out
// of order elements
for (int i = 0; i < arr.length - 1; i++)
{
if (arr[i] > arr[i + 1])
{
ordered = false;
}
}
return ordered;
}
public static void main(String[] args)
{
int[] arrOrder = {1, 2, 3, 4, 5, 6, 7, 8, 9, 42};
int[] arrNotOrder = {2, 1, 3, 4, 5, 6, 7, 8, 9, 42};
// Check if array 1 is ordered or not.
if (inOrder(arrOrder))
{
System.out.println("The array is in order.");
}
else
{
System.out.println("The array is NOT in order.");
}
System.out.println("Expected: The array is in order.");
// Check if array 2 is ordered or not.
if (inOrder(arrNotOrder))
{
System.out.println("The array is in order.");
}
else
{
System.out.println("The array is NOT in order.");
}
System.out.println("Expected: The array is NOT in order.");
}
i) Return true if array contains two adjacent duplicate values.
public static boolean adjacentDupes(int[] arr)
{
// Assume no adjacent dupes.
boolean adjDupes = false;
// Loop through array, checking for duplicates
// next to each other.
for (int i = 0; i < arr.length - 1; i++)
{
if (arr[i] == arr[i + 1])
{
adjDupes = true;
}
}
return adjDupes;
}
public static void main(String[] args)
{
int[] arr1 = {1, 2, 3, 4, 4, 6, 7, 8, 9, 42};
int[] arr2 = {2, 1, 3, 4, 5, 4, 7, 4, 9, 4};
// Check if array 1 has adjacent dupes.
if (adjacentDupes(arr1))
{
System.out.println("Array contains adjacent duplicates.");
}
else
{
System.out.println("Array does NOT contain adjacent duplicates.");
}
System.out.println("Expected: Array contains adjacent duplicates.");
// Check if array 2 has adjacent dupes.
if (adjacentDupes(arr2))
{
System.out.println("Array contains adjacent duplicates.");
}
else
{
System.out.println("Array does NOT contain adjacent duplicates." );
}
System.out.println("Expected: Array does NOT contain adjacent duplicates.");
}
j) Returns true if array contains duplicate values (not necessarily adjacent).
public static boolean containsDuplicates(int[] arr)
{
// Assume no dupes.
boolean dupes = false;
// Loop through array, checking for duplicates
for (int i = 0; i < arr.length; i++)
{
for (int j = i + 1; j < arr.length; j++)
{
if (arr[i] == arr[j])
{
dupes = true;
}
}
}
return dupes;
}
public static void main(String[] args)
{
int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 42};
int[] arr2 = {2, 1, 3, 4, 5, 4, 7, 4, 9, 4};
// Check if array 1 has dupes.
if (containsDuplicates(arr1))
{
System.out.println("Array contains duplicates.");
}
else
{
System.out.println("Array does NOT contain duplicates.");
}
System.out.println("Expected: Array does NOT contain duplicates.");
// Check if array 2 has dupes.
if (containsDuplicates(arr2))
{
System.out.println("Array contains duplicates.");
}
else
{
System.out.println("Array does NOT contain duplicates.");
}
System.out.println("Expected: Array contains duplicates.");
P6.3
import java.util.Scanner;
public class LargestAndSmallestInArray
{
public static void main(String[] args)
{
final int LENGTH = 100;
double[] data = new double[LENGTH];
int size = 0;
// Read inputs
System.out.println("Please enter values, Q to quit:");
Scanner in = new Scanner(System.in);
while (in.hasNextDouble() && size < data.length)
{
data[size] = in.nextDouble();
size++;
}
// Find the largest and smallest value
double largest = data[0];
double smallest = data[0];
for (int i = 1; i < size; i++)
{
if (data[i] > largest)
{
largest = data[i];
}
if (data[i] < smallest)
{
smallest = data[i];
}
}
// Print all values, marking the largest and smallest
for (int i = 0; i < size; i++)
{
System.out.print(data[i]);
if (data[i] == largest)
{
System.out.print(" ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- formula for computing interest on a loan
- computing average product cost calculator
- co signer vs co borrower
- school calendar 2019 bedford county tn
- co signer vs co buyer
- commonwealth financial bedford nh
- co bower vs co signer
- commonwealth financial group bedford nh
- new bedford standard times obituaries
- new bedford standard times newspaper
- bedford tax collector ma
- city of bedford careers