Except where otherwise noted, the contents of this document are Copyright 2010 Stuart Reges and Marty Stepp.
lab document created by Whitaker Brand and Marty Stepp
Goals for today:
for
loops to traverse and process array
data
Which of the following choices is the correct syntax for declaring/initializing an array of integers?
Which of the following choices is the correct syntax for quickly declaring/initializing an array of integers to store a particular list of values?
Fill in the array with the values that would be stored after the code executes:
int[] data = new int[8]; data[0] = 3; data[7] = -18; data[4] = 5; data[1] = data[0]; int x = data[4]; data[4] = 6; data[x] = data[0] * data[1];
index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
---|---|---|---|---|---|---|---|---|
value | 3 | 3 | 0 | 0 | 6 | 9 | 0 | -18 |
Fill in the array with the values that would be stored after the code executes:
int[] list = {2, 18, 6, -4, 5, 1}; for (int i = 0; i < list.length; i++) { list[i] = list[i] + (list[i] / list[0]); }
index | 0 | 1 | 2 | 3 | 4 | 5 |
---|---|---|---|---|---|---|
value | 3 | 24 | 8 | -5 | 6 | 1 |
Arrays
class methodsMethod name | Description |
---|---|
binarySearch(array, value)
|
returns index of value in a sorted array (< 0 if not found) |
copyOf(array, length)
|
returns a new copy of an array |
equals(array1, array2)
|
returns true if the two arrays contain same elements |
fill(array, value)
|
sets every element to the given value |
sort(array)
|
arranges the elements into sorted order |
toString(array)
|
returns a string for the array, such as "[10, 30, -25, 17]" |
double
s, and returns a new
array of rounded int
s:
public static int[] roundAll(double[] realNums) { int[] roundedNums = new int[realNums.length]; for (int i = 0; i < realNums.length; i++) { roundedNums[i] = (int) Math.round(realNums[i]); } return roundedNums; }
roundAll
method from the
previous slide:
import java.util.*; // to use Arrays
public class MyProgram {
public static void main(String[] args) {
double[] realNumbers = {5.5, 7.31, 8.09, -3.234234, 2.0, 0.0};
int[] roundedNumbers = roundAll(realNumbers);
System.out.println(Arrays.toString(roundedNumbers));
}
...
}
// Output: [5, 7, 8, -3, 2, 0]
Suppose that each array at right were passed as a parameter to
the mystery
method below. Fill in the boxes with the array
contents after each method call.
public static void mystery(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] < a[i + 1]) { a[i] = a[i + 1]; } } } |
|
Download the file TriangleCount.java to your machine and open it with jGrasp.
This program explores patterns of digits for what are called the triangle numbers that are described on this wikipedia page. The program counts how many times the next triangle number ends in a particular 2-digit number. For example, the 15th triangle number is 120 and it ends in the 2-digit number 20.
Run the program and you will see an obvious pattern. Most counts are zero and those that aren't are mostly equal to 200. A few are equal to 500 and you can see that from the output. Fill in the numbers below in order that have a count of 500.
3 | 28 | 53 | 78 |
continued on the next slide...
We are going to stop the program in the middle of execution. It has an
if
statement inside the loop that causes it to print a dot
every 250 iterations (to show the progress it has made). Set a stop on
the System.out.print
statement inside the if
and
debug the program.
Now you want to see what is inside the array called count
.
Click on it and drag it out to see its contents. Ask a TA or fellow
student for help if you don't know how to do this. Then fill in the
table below to show the first eight values in the array.
index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
---|---|---|---|---|---|---|---|---|
value | 4 | 4 | 0 | 10 | 0 | 4 | 4 | 0 |
continued on the next slide...
Leave the array viewer open and click on the resume button (the one that
looks like a "play" button). This stops execution the second time
the System.out.print
is about to be executed. Fill in the
values that the first 8 array elements have now.
index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
---|---|---|---|---|---|---|---|---|
value | 8 | 8 | 0 | 20 | 0 | 8 | 8 | 0 |
This is a very long array with 100 total values. Scroll to the far right in the array viewer and fill in the values of the last eight array values.
index | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 |
---|---|---|---|---|---|---|---|---|
value | 0 | 0 | 0 | 8 | 8 | 0 | 0 | 0 |
1 2 3 4 5 6 7 8 9 10 |
// Returns the largest value in the given array.
public static int max(int data[10]) {
int max = 0;
for (int i = 0; i < data[].length(); i++) {
if (array[i] > max) {
max = array[i];
}
}
return max[];
}
|
The above attempted solution to Practice-It problem "max
" has
7 problems. Open Practice-It from the link above, copy/paste this code
into it, and fix the errors. Complete the code so that it passes the test
cases.
[10]
after parameter name; should
write []
(without length) after int
max
at 0
won't work if the
array is all negative. Should initialize max
variable to
be data[0]
and start for
loop at
index 1
[]
after data
here
()
after length
here
array
should be data
array
should be data
[]
after max
here
1 2 3 4 5 6 7 8 9 10 |
// Returns the largest value in the given array. public static int max(int[] data) { int max = data[0]; for (int i = 1; i < data.length; i++) { if (data[i] > max) { max = data[i]; } } return max; } |
PromptNumbers2.java
program
from a previous exercise.
public class PromptNumbers2 { public static void main(String[] args) { int count = console.nextInt(); int[] nums = new int[count]; ... System.out.println("Your numbers in forward order:"); printForward(nums); System.out.println("Your numbers in backward order:"); printBackward(nums); } // Prints the elements of the given array in forward order. public static void printForward(int[] a) { for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } // Prints the elements of the given array in backward order. public static void printBackward(int[] a) { for (int i = a.length - 1; i >= 0; i--) { System.out.println(a[i]); } } }
minGap
Write a method named minGap
that accepts an integer array as a
parameter and returns the minimum 'gap' between adjacent values in the
array. The gap between two adjacent values in a array is defined as the
second value minus the first value. For example, suppose a variable
called array
is an array of integers that stores the following
sequence of values:
int[] array = {1, 3, 6, 7, 12};
The first gap is 2 (3 - 1), the second gap is 3 (6 - 3), the third gap is 1
(7 - 6) and the fourth gap is 5 (12 - 7). Thus, the call
of minGap(array)
should return 1
because that is
the smallest gap in the array. If you are passed an array with fewer than
2 elements, you should return 0
.
Click on the check-mark above to try out your solution in Practice-it!
percentEven
Write a method named percentEven
that accepts an array of
integers as a parameter and returns the percentage of even numbers in the
array as a real number. For example, if a variable named nums
refers to an array of the elements {6, 2, 9, 11, 3}
, then the
call of percentEven(nums)
should return 40.0
. If
the array contains no even elements or no elements at all,
return 0.0
.
Click on the check-mark above to try out your solution in Practice-it!
What values are stored in the array at the comment in main? Note that
the incrementAll
returns void, but does take
an int[]
parameter.
public class ArrayReference {
public static void main(String[] args) {
int[] nums = {2, 4, -1, 3};
incrementAll(nums);
// HERE!
}
public static void incrementAll(int[] data) {
for (int i = 0; i < data.length; i++) {
data[i]++;
}
}
}
index | 0 | 1 | 2 | 3 |
---|---|---|---|---|
value | 3 | 5 | 0 | 4 |
swapAll
Write a method named swapAll
that accepts two arrays of
integers as parameters and swaps their entire contents. You may assume that
the arrays passed are not null and are the same length.
For example, if the following arrays are passed:
int[] a1 = {11, 42, -5, 27, 0, 89}; int[] a2 = {10, 20, 30, 40, 50, 60}; swapAll(a1, a2);
After the call, the arrays should store the following elements:
a1: {10, 20, 30, 40, 50, 60} a2: {11, 42, -5, 27, 0, 89}
stretch
Write a method named stretch
that accepts an array of integers
as a parameter and returns a new array twice as large as the original,
replacing every integer from the original array with a pair of integers,
each half the original. If a number in the original array is odd, then the
first number in the new pair should be one higher than the second so that
the sum equals the original number. For example, if a variable
named list
refers to an array storing the values {18, 7,
4, 24, 11}
, the call of stretch(list)
should return a
new array containing {9, 9, 4, 3, 2, 2, 12, 12, 6, 5}
. (The
number 18 is stretched into the pair 9, 9, the number 7 is stretched into
4, 3, the number 4 is stretched into 2, 2, the number 24 is stretched into
12, 12 and the number 11 is stretched into 6, 5.)
Click on the check-mark above to try out your solution in Practice-it!
copyRange
Write a method called copyRange
that takes as parameters two
arrays a1
and a2
, two starting
indexes i1
and i2
, and a length l
,
and copies the first l
elements of a1
starting at
index i1
into array a2
starting at
index i2
.
For example, if the following arrays are declared:
int[] a1 = {10, 20, 30, 40, 50, 60}; int[] a2 = {91, 92, 93, 94, 95, 96}; copyRange(a1, a2, 0, 2, 3);
After the preceding call, the contents of a2
would
be {91, 92, 10, 20, 30, 96}
. You may assume that the
parameters' values are valid, that the arrays are large enough to hold the
data, and so on.
equals
Write a method named equals
that accepts two arrays of
integers as parameters and returns true
if they contain
exactly the same elements in the same order, and false
otherwise. You may assume that the arrays passed are not null, but they
might not be the same length. Do not call Arrays.equals
in
your solution.
For example, if the following arrays are declared:
int[] a1 = {10, 20, 30, 40, 50, 60}; int[] a2 = {10, 20, 30, 40, 50, 60};
The call of equals(a1, a3)
should return true
.
If you finish all the exercises, try out our Practice-It web tool. It lets you solve Java problems from our Building Java Programs textbook.
You can view an exercise, type a solution, and submit it to see if you have solved it correctly.
Choose some problems from Chapter 7 and try to solve them!