Você está na página 1de 74

Chapter XV

Two-Dimensional Arrays and


the AP Picture Labs
Chapter XV Topics

15.1 Introduction
15.2 Declaring a Static 2D Array
15.3 Two-Dimensional Array Output
15.4 2D Arrays and the length Field
15.5 Two-Dimensional Dynamic Arrays
15.6 Introduction to Number Systems
15.6.1 Counting in Other Number Systems
15.6.2 Counting in Base-16
15.6.3 Converting to Base-10
15.6.4 Converting Base-2 to Base-10
15.6.5 Converting Base-10 to Any Base
15.7 The AP® Picture Labs
15.7.1 AP® Picture Experiment 01
15.7.2 AP® Picture Experiment 02
15.7.3 AP® Picture Experiment 03
15.7.4 AP® Picture Experiment 04
15.7.5 AP® Picture Experiment 05
15.7.6 AP® Picture Experiment 06
15.8 Summary

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 1


15.1 Introduction

All the array programs – both static arrays and dynamic arrays had something in
common. They have all been examples of one-dimensional (1D) arrays. The term
one-dimensional may have been used a few times without much emphasis on the
concept. It is easier to discuss the dimension of an array when there is the
opportunity to make comparisons. In real life you are surrounded by examples of
both one-dimensional and two-dimensional arrays. A street is a one-dimensional
array of homes. Reserved seats at a football stadium and seats in an airplane
represent a two-dimensional array. Take a look at the seating in figure 15.1. An
array of twenty desks is shown. These twenty desks can be viewed as a linear
sequence of seats, which are numbered from 1 to 20. We could make a closer
analogy to computer language arrays and number the seats from 0 to 19.
However, we can select to represent the seats in a different manner that
realistically resembles the physical desk layout better using a two-dimensional
array.

Figure 15.1
[16] [17] [18] [19] [20]
Jaxon Braxton Remy Michelle Ingrid
[11] [12] [13] [14] [15]
Alec Mariana Mike Haley Maddox
[06] [07] [08] [09] [10]
Diana Jessica Brenda David Anthony
[01] [02] [03] [04] [05]
Isolde John Greg Maria Heidi

The classroom has twenty desks and each desk has a label or index. Labels start at
[01] and end at [20]. This is all simple enough, but the seating chart resembles a
matrix or two-dimensional array more closely. The class has rows and columns.
In fact there are four rows of desks and five columns of desks.

It is possible to designate each student with double labels, one for row and a
second one for column. On the second seating chart, in figure 15.2, you will see
the same classroom and the same desk arrangement, but this time there are two
labels for each seat. The first index, by convention, indicates the row location and
the second index labels the column.

Page 2 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Figure 15.2
[4][1] [4][2] [4][3] [4][4] [4][5]
Jaxon Braxton Remy Michelle Ingrid
[3][1] [3][2] [3][3] [3][4] [3][5]
Alec Mariana Mike Haley Maddox
[2][1] [2][2] [2][3] [2][4] [2][5]
Diana Jessica Brenda David Anthony
[1][1] [1][2] [1][3] [1][4] [1][5]
Isolde John Greg Maria Heidi

The example of the seating chart actually goes a little against another convention.
Two-dimensional arrays are frequently shown as a matrix of values, and the first
row in the matrix is normally shown at the top of the matrix. This seating chart
has intentionally been displayed from the point of view of the instructor. Using
two values to indicate a location is very common. A Football ticket indicates
something like Row K, Seat 34, and an airline boarding pass may say Row 29,
Seat D. In the world of mathematics, science and business, a matrix of numbers is
used for many types of calculations.

15.2 Declaring a Static 2D Array

Declaring a static two-dimensional array holds few surprises. Everything you


have learned about static one-dimensional arrays in the areas of declarations and
definitions is identical. You need an array identifier along with a data type for
each element of the array. You also need the new operator to define the size of the
array and allocate sufficient memory.

There is only one small difference you will see in program Arrays01.java, shown
in figure 15.3, and that is the need to provide two sets of brackets. The first set of
brackets dimensions the number of rows and the second set of brackets
dimensions the number of columns in the array. In the first 2D array example
every array element is accessed individually. This works, and it is manageable for
a small array of two rows by three columns.

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 3


Figure 15.3

// Arrays01.java
// This program introduces 2D Java static arrays.
// For 2D arrays two sets of index operators are needed.
// The first set of index brackets stores the rows value.
// The second set of index operators stores the cols value.

public class Arrays01


{
public static void main(String[ ] args)
{
int twoD[ ][ ]; // declaration of two-dimensional integer array
twoD = new int[2][3]; // new 2D array is constructed with 2 rows and 3 cols
twoD[0][0] = 1;
twoD[0][1] = 2;
twoD[0][2] = 3;
twoD[1][0] = 4;
twoD[1][1] = 5;
twoD[1][2] = 6;

System.out.print(twoD[0][0] + " ");


System.out.print(twoD[0][1] + " ");
System.out.print(twoD[0][2] + " ");
System.out.println();
System.out.print(twoD[1][0] + " ");
System.out.print(twoD[1][1] + " ");
System.out.print(twoD[1][2] + " ");
}
}

Program Arrays02.java, in figure 15.4, is the typical approach used with 2D


arrays. Like the earlier 1D arrays, loop control structures are used. In the case of
2D arrays two separate loops are needed. An outer loop controls the rows and the
inner loop controls the columns of the 2D array.

Page 4 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Figure 15.4

// Arrays02.java
// A set of nested loops is used with 2D arrays to assign and display individual values.
// Additionally, the declaration of the 2D array is done in one statement.

public class Arrays02


{
public static void main(String[ ] args)
{
int twoD[ ][ ] = new int[2][3]; // 2D array declaration in one statement.

int count = 1;
for (int row = 0; row < 2; row++)
{
for (int col = 0; col < 3; col++)
{
twoD[row][col] = count;
count++;
}
}
for (int row = 0; row < 2; row++)
{
for (int col = 0; col < 3; col++)
{
System.out.print(twoD[row][col] + " ");
}
System.out.println();
}
}
}

The handy initializer list, shown with the 1D static arrays, also is available for the
2D static arrays. It helps to realize that technically speaking there are no 2D
arrays. A 2D array is really a 1D array where every array element is a 1D array.
In other words, a 2D array is an array of arrays. Program Arrays03.java, in
figure 15.5, uses an initializer list. Observe the comma placement and you see the
array of arrays concept visualized. A second approach, which visually displays
the 2D matrix, is also shown in comments.

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 5


Figure 15.5

// Arrays03.java
// This program demonstrates how to use an initializer list.
// Commented lines 15 and 16 show a matrix style.

public class Arrays03


{
public static void main(String[ ] args)
{
int twoD[ ][ ] = { {1,2,3}, {4,5,6} };

// int twoD[ ][ ] = { {1,2,3},


// {4,5,6} };

for (int row = 0; row < 2; row++)


{
for (int col = 0; col < 3; col++)
{
System.out.print(twoD[row][col] + " ");
}
System.out.println();
}
}
}

Program Arrays04.java, in figure 15.6, may seem similar to earlier programs, but
it displays a very common error that causes array programs to crash during
program execution.

The problem with this program is that the number of rows is confused with the
number of columns. The matrix has 7 rows and 5 columns. When the program
attempts to display 5 rows with 7 columns, the program crashes with a runtime
exception. More information about Java exceptions will be discussed in a later
chapter. The program crashes because an index value is too big.

Page 6 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Figure 15.6

// Arrays04.java
// This program demonstrates what happens when rows and columns are confused.
// A matrix of 7 rows and 5 columns is created.
// The program attempts to display 5 rows and 7 columns.

public class Arrays04


{
public static void main(String[ ] args)
{
int k = 1;
int matrix[ ][ ] = new int[7][5]; // 7 rows with 5 columns
for (int r = 0; r < 7; r++)
for (int c = 0; c < 5; c++)
{
matrix[r][c] = k;
k++;
}
System.out.println();

for (int r = 0; r < 5; r++) // should be 7


{
for (int c = 0; c < 7; c++) // should be 5
System.out.print(matrix[r][c] + " ");
System.out.println();
}
}
}

2D arrays normally involve matrices and matrices are usually displayed in


a row x col configuration. This does involve lining up the columns correctly for a
pleasing output display. Program Arrays05.java, in figure 15.7, is logically
correct and the output is also correct, but the matrix does not look very neat when
the numerical values have a different number of digits.

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 7


Figure 15.7

// Arrays05.java
// This program allows the user to specify the number of rows and columns.
// Note that the output will not line up nicely as it combines single,
// double and triple digit numbers.

import java.util.Scanner; // necessary to use the <Scanner> class

public class Arrays05


{
public static void main(String[ ] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of rows --> ");
int numRows = input.nextInt();
System.out.print("Enter the number of columns --> ");
int numCols = input.nextInt();
System.out.println("\n");
int k = 1;
int matrix[ ][ ] = new int[numRows][numCols];
for (int r = 0; r < numRows; r++)
for (int c = 0; c < numCols; c++)
{
matrix[r][c] = k;
k++;
}
System.out.println();
for (int r = 0; r < numRows; r++)
{
for (int c = 0; c < numCols; c++)
System.out.print(matrix[r][c] + " ");
System.out.println();
}
}
}

Page 8 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


15.3 Two-Dimensional Array Output

When two-dimensional arrays store numerical data, it is customary to display the


output of such arrays in the row x col format shown in the previous program.
That program also shows that numbers of different sizes can make the resulting
output undesirable. One solution is to create a DecimalFormat object, which can
then control the output of numerical data. Program Arrays06.java, in figure
15.08 uses the DecimalFormat class to make all numbers display as 3 digit
numbers. Now all the numbers line up as desired.

Figure 15.8

// Arrays06.java
// This program demonstrates using <DecimalFormat> with 2D arrays.
// By using <DecimalFormat> we can make output line up properly.

import java.text.DecimalFormat; // necessary to use the <DecimalFormat> class


import java.util.Scanner; // necessary to use the <Scanner> class

public class Arrays06


{
public static void main(String[ ] args)
{
DecimalFormat threeDigits = new DecimalFormat("000");
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of rows --> ");
int numRows = input.nextInt();
System.out.print("Enter the number of columns --> ");
int numCols = input.nextInt();
System.out.println("\n");
int k = 1;
int matrix[][] = new int[numRows][numCols];
for (int r = 0; r < numRows; r++)
for (int c = 0; c < numCols; c++)
{
matrix[r][c] = k;
k++;
}
System.out.println();

for (int r = 0; r < numRows; r++)


{
for (int c = 0; c < numCols; c++)
System.out.print(threeDigits.format(matrix[r][c]) + " ");
System.out.println();
}
}
}

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 9


Figure 15.8 Continued

In this chapter we speak about two-dimensional arrays. It certainly appears that


the arrays have two dimensions. You do see a double set of brackets for two index
values. The truth is we only have one-dimensional arrays and some of these arrays
are manipulated in a manner that makes them seem to be two-dimensional.

This may seem odd, but there is compelling evidence for this argument. Ask
yourself, what can you store in a one-dimensional array? Well there are numbers,
characters, strings that can be stored and yes you can also store an array in each
element of an existing array. This becomes an array of arrays.

In real life that is actually what happens. Suppose you go to a concert with a
reserved seat ticket. Your ticket states Row H, Seat 17. Now here is a question:
Do you go straight to your seat? I would rather doubt that. Your first mission is to
find Row H. You walk down the aisle and there is H. At this location you are now
looking at a one-dimensional array of seats. This one-dimensional array is called
H. The concert venue is a two-dimensional array of seats, but it can also be called
a one-dimensional array of rows, which then in turn is another one-dimensional
array of seats.

You may be puzzled, because you have just started a section on 2D array output
and this array of arrays seems to go off to some weird tangent. There is a reason
for this explanation. The next program example shows how to use the special
for..each loop with a 2D array. The format of the two-dimensional for..each loop
is based on the array of arrays logic.

Page 10 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Program Arrays07.java, in figure 15.9, uses a displayMatrix method and inside
the method a set of nested for..each loops are used to display the matrix array.
Examine the program carefully. How is a 2D array passed as a parameter? Also
how are for..each nested such that elements in a 2D array are accessed?

Figure 15.9

// Arrays07.java
// This program uses the <for..each> loop structure to display the matrix.
// In this case it is not necessary to use the height and width of the array.

public class Arrays07


{
public static void main(String[ ] args)
{
int[ ][ ] mat = { {1,2,3,4},
{5,6,7,8} };
displayMatrix(mat);
}

public static void displayMatrix(int[ ][ ] matrix)


{
for (int[ ] row : matrix)
{
for (int number : row)
System.out.print(number + " ");
System.out.println();
}
}
}

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 11


Does the nested for..each loop, in figure 15.9, make sense? The outer loop - in a
concise, Java statement - says the following in English ...

For each array element row in matrix, which is an int array,


do the following ...
Well, inside the outer for..each loop is an inner for..each loop, which continues
with its own Java logic and once again we can say in English ...

For each array element number in row, which is an int,


display the number.

for..each Loop Structure Limitations

The for..each loop structure is read only for any type of data
structure. This is true for the one-dimensional array as well as
the two-dimensional array.

Furthermore, the for..each loop will access every element of


the array and cannot be limited to smaller section.

15.4 2D Arrays and the length Field

The length data attribute or field was introduced earlier to determine the number
of elements in a static array. At that time only one-dimensional arrays had been
shown and a natural question is how size is handled with two-dimensional arrays?

Consider program Arrays08.java, in figure 15.10. The length field is used in the
loop, pretty much as it was done with a 1D array. It may seem odd that the same
length value is used for both loops. The output appears correct. Is this the way to
use length? Does it apply both to the number of rows and also to the number of
columns in a 2D array?

Page 12 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Figure 15.10
// Arrays08.java
// This program creates a 3 X 3 2D array and uses a method
// to display the array elements.
// The <length> field is used for both row and column length.

public class Arrays08


{
public static void main(String[ ] args)
{
int[ ][ ] mat = { {1,2,3},
{4,5,6},
{7,8,9}};
displayMatrix(mat);
}

public static void displayMatrix(int[][] m)


{
for (int r = 0; r < m.length; r++)
{
for (int c = 0; c < m.length; c++)
System.out.print(m[r][c] + " ");
System.out.println();
}
System.out.println();
}
}

This two-dimensional array seems to work quite nicely with the aid of length.
There is a concern though, because a square matrix with three rows and three
columns is used. The same length field is used for row size and column size.
How well will this approach work if the matrix is not square?

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 13


Program Arrays09.java, in Figure 15.11, has a 2 X 4 two-dimensional array.
The output shows a 2 X 2 matrix. It appears that length, as it is used in the last
two programs, is the value of the number of rows.

Figure 15.11

// Arrays09.java
// The same <displayMatrix> method is used to display a
// 2 X 4 2D array. This time the method does not display correctly.

public class Arrays09


{
public static void main(String[ ] args)
{
int[ ][ ] mat = { {1,2,3,4},
{5,6,7,8} };
displayMatrix(mat);
}

public static void displayMatrix(int[ ][ ] m)


{
for (int r = 0; r < m.length; r++)
{
for (int c = 0; c < m.length; c++)
System.out.print(m[r][c] + " ");
System.out.println();
}
System.out.println();
}
}

In the last section it was mentioned that a two-dimensional array is in fact a one-
dimensional array of one-dimensional arrays. Program Arrays10.java, in figure
15.12, takes this new information and tries a different approach. m.length is used
for the row size and then m[0].length is used for the column size.

Page 14 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Figure 15.12

// Arrays10.java
// A 2D array is a 1D array of arrays.
// This program uses the m[0].length field properly.

public class Arrays10


{
public static void main(String[ ] args)
{
int[ ] [ ] mat = { {1,2,3,4},
{5,6,7,8} };
displayMatrix(mat);
}

public static void displayMatrix(int[ ][ ] m)


{
for (int r = 0; r < m.length; r++)
{
for (int c = 0; c < m[0].length; c++)
System.out.print(m[r][c] + " ");
System.out.println();
}
System.out.println();
}
}

Program Arrays11.java, in Figure 15.13, shows a two dimensional array with


five rows, but the number of columns vary. The first row has one element; the
second row has two elements, and so on. The displayMatrix method handles this
varying length stuff without difficulty. m.length is used for the number of rows.
The number of rows is a single value and does not change. On the other hand,
each row has a different number of columns. m[r].length is used for the number
of columns. Since r is a variable that stores the index value for each row,
m[r].length will then store the number of columns for each different row.

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 15


Figure 15.13

// Arrays11.java
// This program demonstrates how to construct an irregular two-dimensional array
// in the shape of a triangle, using a "ragged" array.
// It also shows how to use length for different column sizes.

public class Arrays11


{
public static void main(String[ ] args)
{
int[ ][ ] mat = { {1},
{1,2},
{1,2,3},
{1,2,3,4},
{1,2,3,4,5} };
displayMatrix(mat);
}

public static void displayMatrix(int[ ][ ] m)


{
for (int r = 0; r < m.length; r++)
{
for (int c = 0; c < m[r].length; c++)
System.out.print(m[r][c] + " ");
System.out.println();
}
System.out.println();
}
}

Page 16 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


AP® Examination Alert

Two-dimensional ragged arrays, as shown in the example


below are not tested on the AP®CS Examination.
int[ ][ ] mat = { {1},
{1,2},
{1,2,3},
{1,2,3,4},
{1,2,3,4,5} };

The new AP® Computer Science curriculum for the 2015 examination places a
special emphasis on the fact that two-dimensional arrays are one-dimensional
arrays. Another, yet different example is shown by Arrays12.java, in figure
15.14. The program starts with the declaration of a two-dimensional array and
then - without any problems - displays separate one-dimensional arrays.

Figure 15.14

// Arrays12.java
// In this program we explorer the "array of array" concept further.
// Notice how the "2D Array" uses a single set of [ ] index operators.

public class Arrays12


{
public static void main(String[ ] args)
{
int[ ][ ] mat = { {1,2,3}, {4,5,6}, {7,8,9} };
System.out.println("mat: " + mat);
System.out.println("mat[0]: " + mat[0]);
System.out.println("mat[1]: " + mat[1]);
System.out.println("mat[2]: " + mat[2]);
}
}

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 17


One final example on this important issue. This time Arrays13.java, in figure
15.15, starts with three one-dimensional arrays, which then are used to create a
two-dimensional array. And with this program example we can now move on.

Figure 15.15

// Arrays13.java
// In this program 1D arrays are created first and then used to create a 2D array.

public class Arrays13


{
public static void main(String[ ] args)
{
int[ ] list1 = {1,2,3};
int[ ] list2 = {4,5,6};
int[ ] list3 = {7,8,9};
int[ ][ ] mat = new int[3][3];

mat[0] = list1;
mat[1] = list2;
mat[2] = list3;

displayMatrix(mat);
}

public static void displayMatrix(int[ ][ ] m)


{
for (int r = 0; r < m.length; r++)
{
for (int c = 0; c < m.length; c++)
System.out.print(m[r][c] + " ");
System.out.println();
}
}
}

Page 18 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


15.5 Two-Dimensional Dynamic Arrays

The ArrayList class is a very practical one-dimensional, dynamic array with


many convenient methods. It is rare to see this class used for two-dimensional
arrays and the static 2D array is much easier to declare and manipulate. Yet it is
possible to create a two dimensional, dynamic array with the ArrayList class, as
shown in figure 15.16 with program Arrays14.java. Pay particular attention to
the syntax of the nested generics declaration.

Figure 15.16

// Arrays14.java
// This program demonstrates how to declare a two-dimensional
// dynamic array.
// It also demonstrates two different output approaches.

import java.util.ArrayList;

public class Arrays14


{
public static void main (String[ ] args)
{
ArrayList<String> cats = new ArrayList<String>();
cats.add("Lions");
cats.add("Tigers");

ArrayList<String> swimmers = new ArrayList<String>();


swimmers.add("Whales");
swimmers.add("Dolphins");

ArrayList<String> primates = new ArrayList<String>();


primates.add("Gorillas");
primates.add("Chimpanzees");

ArrayList<ArrayList<String>> mammals = new ArrayList<ArrayList<String>>();


mammals.add(cats);
mammals.add(swimmers);
mammals.add(primates);

System.out.println(mammals);
System.out.println();

for (ArrayList<String> mammal: mammals)


{
for (String animal: mammal)
System.out.println(animal);
System.out.println();
}
}
}

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 19


Figure 15.16 Continued

Program Arrays15.java, in figure 15.17, gives an idea that dynamic arrays are
more difficult to handle than static arrays for 2D applications. This next program
example is almost identical to the previous program but accesses individual array
locations directly. This is necessary if values have to be altered.

Figure 15.17

// Arrays15.java
// This program example demonstrates how to use the original <for>
// loop structure to display dynamic two-dimensional arrays.

import java.util.ArrayList;

public class Arrays15


{
public static void main (String[ ] args)
{
ArrayList<String> cats = new ArrayList<String>();
cats.add("Lions");
cats.add("Tigers");
ArrayList<String> swimmers = new ArrayList<String>();
swimmers.add("Whales");
swimmers.add("Dolphins");
ArrayList<String> primates = new ArrayList<String>();
primates.add("Gorillas");
primates.add("Chimpanzees");

ArrayList<ArrayList<String>> mammals = new ArrayList<ArrayList<String>>();


mammals.add(cats);
mammals.add(swimmers);
mammals.add(primates);

Page 20 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


for (int row = 0; row < mammals.size(); row++)
{
for (int col = 0; col < mammals.get(row).size(); col++)
System.out.println(mammals.get(row).get(col));
System.out.println();
}
}
}

Figure 15.17 Continued

The nested loops in figure 15.18 gives a convenient, same-page, comparison of


the program code used to display the contents of a dynamic 2D array and a static
2D array. This only compares the display of 2D array. The actual manipulation of
a dynamic, 2D array is not nearly as convenient as a static array. If there is a need
for a dynamic array, it may be better to use the ArrayList to create a special class
that specifically is designed to handle 2D arrays.

Figure 15.18

for (int r = 0; r < m.length; r++)


{
for (int c = 0; c < m[0].length; c++)
System.out.print(m[r] [c] + " ");
System.out.println();
}

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 21


15.6 Introduction to Number Systems

Computer science programming requires proficiency with mathematics that


involves conversion between different numbers systems. Computer systems store
information, and compute information in base-2. Human beings prefer to handle
base-10 number systems. In the majority of computer applications, and even
program language compilers, the conversion between base-2 and base-10 is
handled quietly in the background by the application program or language
compiler program. This unit on number systems is intentionally placed in this
chapter to assist in understanding the AP Picture Labs that follow later.

Calculator Warning

The AP Computer Science Examination does not allow the use


of calculators. It is vitally important that you learn to do all
computations on paper. Number systems is one of the topics
that may be tested on the AP Computer Science Examination.

15.6.1 Counting in Other Number Systems

Counting is something that you will likely take for granted, at least counting in
base-10. This mathematical excursion starts by taking a new look at how we count
in base-10, and how counting is done in other number systems as well. In base-10
there are ten different single digits from 0 to 9. Counting in base-10 requires
cycling through these ten digits. Every time 9 is reached the counting starts over
at 0, and at the same time the digit in the next column is incremented by one.
Consider the following pattern.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
......................................................
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

Using the pattern we observe with base-10 counting lets us set up a set of rules
and then use this set of rules to count in other bases as well. Keep in mind that
there is nothing magic about counting in base-10. Base-10 is only easier for you

Page 22 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


because you have familiarity. You learned multiplication tables in base-10 and
you are constantly surrounded by base-10. However, consider the fact that there
are 60 seconds in a minute, 60 minutes in an hour. How about 12 inches to a foot,
3 feet to a yard, and 1,760 yards to a mile? Not everything is done in base-10.
You may argue that the Metric measurement system is simpler than the English
measurement system, precisely because it is done in base-10. This seems like a
good argument, but the truth is that the metric system stays consistently with a
single base - base-10 - and it is a base that people are familiar with. Switching
from inches to feet, to yards, to miles involves also switching different conversion
systems. If the English system used base-8 throughout its conversions, and you
grew up with base-8, such a system would be as easy as the Metric system is
today. So what about these rules?

Counting Rules For All Bases

The number of single digits is equal to the base value.


Base-10 has 10 single digits
Base-8 has 8 single digits
Base-16 has 16 single digits
Base-2 has 2 single digits

The value of the base is expressed as 10.


8 in base-8 is 10
4 in base-4 is 10
2 in base-2 is 10
16 in base-16 is 10

The largest single digit is one less than the base value.
The largest digit in base-10 is 9
The largest digit is base-5 is 4
The largest digit in base-8 is 7
The largest digit in base-2 is 1
The largest digit in base-16 is F (base-16 needs digits not used in base-10)

When the largest digit is reached, counting starts over at 0,


and the next place holder is incremented by 1.
Base 5: 0 1 2 3 4 10 11 12 13 14 20 21 22 23 24 30
Base 4: 0 1 2 3 10 11 12 13 20 21 22 33 100 101
Base 3: 0 1 2 10 11 12 20 21 22 100 101 102 110 111 112 120
Base 2: 0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 23


It is easy to keep on talking about how to count. At this stage it is probably
simpler to look at several bases and follow the counting scheme of each base as it
goes from 0 to 33, at least in base-10 that is. Base-3 and base-2 are shown last.
Bases with few digits tend to be confusing because the numbers change so rapidly
and so drastically. Look at base-5 and base-8 first to establish the counting
pattern, and then check out base-3 and base-2.

Base 10 Base 5 Base 8 Base 3 Base-2


0 0 0 0 0
1 1 1 1 1
2 2 2 2 10
3 3 3 10 11
4 4 4 11 100
5 10 5 12 101
6 11 6 20 110
7 12 7 21 111
8 13 10 22 1000
9 14 11 100 1001
10 20 12 101 1010
11 21 13 102 1011
12 22 14 110 1100
13 23 15 111 1101
14 24 16 112 1110
15 30 17 120 1111
16 31 20 121 10000
17 32 21 122 10001
18 33 22 200 10010
19 34 23 201 10011
20 40 24 202 10100
21 41 25 210 10101
22 42 26 211 10110
23 43 27 212 10111
24 44 30 220 11000
25 100 31 221 11001
26 101 32 222 11010
27 102 33 1000 11011
28 103 34 1001 11100
29 104 35 1002 11101
30 110 36 1010 11110
31 111 37 1011 11111
32 112 40 1012 100000
33 113 41 1020 100001

Page 24 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Do you feel that you can count in different bases now? You will find out soon
enough when you try to do some exercises. However, before you are asked to
show your understanding, you should first study some sample exercises and see if
they make sense to you.

Starting with this first set of exercises you will see a pattern that will be followed
throughout this number system handout. The first group of exercises, 5 in this
case, provide solutions. The second group of exercises are your responsibility
either in class or to do at home.

Exercise 1.1:
List the next 10 base-8 numbers after 321

322 323 324 325 326 327 330 331 332 333

Exercise 1.2:
List the next 10 base-4 numbers after 121

122 123 130 131 132 133 200 201 202 203

Exercise 1.3:
List the next 10 base-2 numbers after 101

110 111 1000 1001 1010 1011 1100 1101 1110 1111

Exercise 1.4:
List the next 10 base-9 numbers after 105

Exercise 1.5:
List the next 10 base-8 numbers after 256

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 25


15.6.2 Counting In Base-16

Counting in base-16 is significant in computer science. You will see that all the
computer memory addresses or references are displayed in base-16 or
hexadecimal. Furthermore, the MAC or physical address of a computer is also a
base-16 number. There are unique properties between base-2 and base-16 that
make base-16 a logical choice for number representation in a computer. A few
sections later we will investigate these properties. Right now you need to learn
how to count in base-16.

Base-16 was intentionally not placed in the previous counting section. Every base
in the previous section was smaller than base-10. This was convenient and it
insured that you always used some familiar single digit. The story changes with
base-16 because now it is necessary to fabricate some new single digit numerals.
Base-16 requires the use of 16 single digits. Starting with value 10 base-16 starts
to use letter A and continues with B, C, D, E and F. This looks quite bizarre at
first, but after a while you get used to it. Check out the table below that counts the
first one hundred base-16 numbers.

B-10 B-16 B-10 B-16 B-10 B-16 B-10 B-16 B-10 B-16
1 1 21 15 41 29 61 3d 81 51
2 2 22 16 42 2a 62 3e 82 52
3 3 23 17 43 2b 63 3f 83 53
4 4 24 18 44 2c 64 40 84 54
5 5 25 19 45 2d 65 41 85 55
6 6 26 1a 46 2e 66 42 86 56
7 7 27 1b 47 2f 67 43 87 57
8 8 28 1c 48 30 68 44 88 58
9 9 29 1d 49 31 69 45 89 59
10 a 30 1e 50 32 70 46 90 5a
11 b 31 1f 51 33 71 47 91 5b
12 c 32 20 52 34 72 48 92 5c
13 d 33 21 53 35 73 49 93 5d
14 e 34 22 54 36 74 4a 94 5e
15 f 35 23 55 37 75 4b 95 5f
16 10 36 24 56 38 76 4c 96 60
17 11 37 25 57 39 77 4d 97 61
18 12 38 26 58 3a 78 4e 98 62
19 13 39 27 59 3b 79 4f 99 63
20 14 40 28 60 3c 80 50 100 64

Page 26 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Exercise 2.1:
List the next 10 base-16 numbers after 100

101 102 103 104 105 106 107 108 109 10a

Exercise 2.2:
List the next 10 base-16 numbers after 64

65 66 67 68 69 6a 6b 6c 6d 6e

Exercise 2.3:
List the next 10 base-16 numbers after 1001

1001 1002 1003 1004 1005 1006 1007 1008 1009 100a

Exercise 2.4:
List the next 10 base-16 numbers after abc

Exercise 2.5:
List the next 10 base-16 numbers after 999

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 27


15.6.3 Converting to Base-10
Base-10 is limited to 10 different single digits. Values ten, and larger, cannot be
represented as a single digit. This problem is handled with special place holders.
Place holders indicate the true value of a digit, which depends on the position of a
digit in a number. The table below shows the place holder values for a base-10
number, 1,234,567. The top row represents the place holder value. The second
row displays the single digits in their respective position. The bottom row shows
the actual value represented by each single digit.

Place Holder 1,000,000 100,000 10,000 1,000 100 10 1


Digit Display 1 2 3 4 5 6 7
Digit Value 1,000,000 200,000 30,000 4,000 500 60 7

The next table is going a step further. This time each place holder will also be
shown as a power of base-10. Row-2 will now represent the power of each place
holder value. Row-3 will show the base and the appropriate exponent. The next
four rows show how the actual value of each place-holding digit is computed.
Row-4 computes the place holder value by raising the base 10 to the indicated
power for its position. Row-5 is the actual single digit that occupies the position
in the number. Row five shows how to multiply the digit times the place holder
value, and the bottom row shows the actual value of a digit after computation.

Number 1,234,567 base-10


Power 6 5 4 3 2 1 0
BasePower 106 105 104 103 102 101 100
Place Holder 1,000,000 100,000 10,000 1,000 100 10 1
Digit Display 1 2 3 4 5 6 7
Expanded 1 x 106 2 x 105 3 x 104 4 x 103 5 x 102 6 x 101 7 x 100
Digit Value 1,000,000 200,000 30,000 4,000 500 60 7

So far this may seem like a serious what is the big deal anyway? The big deal is
that all numbers in any base can be expressed in expanded notation, and this
expanded notation will be used for conversion between bases. Consider the
following expanded notation for numbers in base-5, base-8, base-16, and base4.

Page 28 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


3214 base-5 = 3 x 53 + 2 x 52 + 1 x 51 + 4 x 50

70416 base-8 = 7 x 84 + 0 x 83 + 4 x 82 + 1 x 81 + 6 x 80

5a9d base-16 = 5 x 163 + a x 162 + 9 x 161 + d x 160

3204 base-4 = Incorrect base-4 number

3204 base-4 is intentionally not expanded because it is not a correct number.


Digit 4 is not possible in base-4. Watch out for this type of problem. You are so
used to using digits in the range 0 . . 9 that you may not realize the proper digit
range in bases smaller than 10.

If number expansion makes sense to you, you can then take any number in any
base and determine place holder values. You can also create a general method for
expansion for a number with base-Q.

54321 base-Q = 5 x Q4 + 4 x Q3 + 3 x Q2 + 2 x Q1 + 1 x Q0

Perhaps you are wondering what is the use of all of this expansion business is?
Excellent question. With number expansion you can convert a number from any
base into a base-10 number. For instance, let us look at 3214 base-5 again, and
this time we will do some additional calculations beyond the number expansion.

3214 base-5 = 3 x 53 + 2 x 52 + 1 x 51 + 4 x 50

3214 base-5 = 3 x 125 + 2 x 25 + 1 x 5 + 4 x 1

3214 base-5 = 375 + 50 + 5 + 4

3214 base-5 = 434 base-10

Did that computation make sense? The whole point is that number representation
is the exact same in any base. The only difference is the value of the base. The 3
in 3215 base-5 has a value of 375. The same three in 3215 base-4 has a different
value because the base is different, and the value is 3 x 43 = 3 x 64 = 192.
Check out the following five exercise examples, and then try it on your own.

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 29


Exercise 3.1:
213 base-4 = ??? base-10

2 x 42 + 1 x 4 1 + 3 x 40 =
2 x 16 + 1 x 4 + 3 x 1 =
32 + 4 + 3 =
39 base-10

Exercise 3.2:
2134 base-5 = ??? base-10

2 x 53 + 1 x 5 2 + 3 x 51 + 4 x 50 =
2 x 125 + 1 x 25 + 3 x 5 + 4 x 1 =
250 + 25 + 15 + 4 =
294 base-10

Exercise 3.3:
175 base-8 = ??? base-10

1 x 82 + 7 x 8 1 + 5 x 80 =
1 x 64 + 7 x 8 + 5 x 1 =
64 + 56 + 5 =
125 base-10

Base-16 numbers require one extra step. It is not sufficient to use the base-10
place holder values and use them for conversion. The base-16 single digits may
well include values like a, b, c, d, e and f. Any time a base-16 includes such letter
digits, it will be necessary to convert the letter digits to their equivalent base-10
(10, 11, 12, 13, 14 and 15) value before you do any final computations.

Page 30 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Exercise 3.4:
1fa base-16 = ??? base-10

1 x 162 + f x 161 + a x 160 =


1 x 256 + f x 16 + a x 1 =
1 x 256 + 15 x 16 + 10 x 1 =
256 + 240 + 10 =
506 base-10

Exercise 3.5:
101101 base-2 = ??? base-10

1 x 25 + 0 x 2 4 + 1 x 23 + 1 x 22 + 0 x 21 + 1 x 20 =
1 x 32 + 0 x 16 + 1 x 8 + 1 x 4 + 0 x 2 + 1 x 1 =
32 + 0 + 8 + 4 + 0 + 1 =
45 base-10

Exercise 3.6:
111 base-3 = ??? base-10

Exercise 3.7:
111 base-4 = ??? base-10

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 31


Exercise 3.8:
321 base-16 = ??? base-10

Exercise 3.9:
3024 base-5 = ??? base-10

Exercise 3.10:
1111 base-2 = ??? base-10

Observant students may argue that the conversion method for base-2 does not
require all the steps that are used for other numbers. You may note various
shortcuts that can be used. If you know such shortcuts or if you intuitively sense
that there must be a simpler way, well you are completely correct. However, at
this stage the motivation is to demonstrate a common approach that works for any
base that needs to be converted to base-10.

The next section will address the specific nature of converting numbers between
base-2 and base-10. There will also be some special attention devoted to the
relationship between base-2 and base-16 numbers.

Page 32 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


15.6.4 Converting Base-2 to Base-10

This section may seem redundant at first. Earlier in this chapter you were shown
how to convert numbers from any base to base-10. This type of conversion
includes converting base-2 to base-10. It turns out that there is some extra
baggage required for numbers with a base greater than 2 that is not necessary for
base-2 numbers. Consider the following conversion.

101101 base-2 = ??? base-10


1 x 25 + 0 x 2 4 + 1 x 2 3 + 1 x 22 + 0 x 2 1 + 1 x 20 =
1 x 32 + 0 x 16 + 1 x 8 + 1 x 4 + 0 x 2 + 1 x 1 =
32 + 0 + 8 + 4 + 0 + 1 =
45 base-10

It is pretty silly to multiply a number times 1. That made sense with larger base
numbers, but in base-2 there is never a multiply issue. It is also convenient to set
up a chart of binary numbers. You can start on the right with number 1, and
double each number as you move to the left. With such a chart, conversion
becomes easier and more efficient.

101101 base-2 = ??? base-10


128 64 32 16 8 4 2 1
1 0 1 1 0 1
32 8 4 1
32 + 8 + 4 + 1 = 45 base-10

Do not think that you should be creating a chart, such as the one above for each
problem that you compute? The point is to take out a piece of scratch paper, write
down a series of binary numbers and write the base-2 number below your chart.
Think of 1 as add, and 0 as skip. Add up all the values below the ones to get the
equivalent base-10 number. The exercises that follow will use the matrix grid to
help neatly identify the number locations. For your own computation the matrix
should not be necessary for each problem.

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 33


Exercise 4.1:
1111 base-2 = ??? base-10
128 64 32 16 8 4 2 1
1 1 1 1
8 4 2 1
8 + 4 + 2 + 1 = 15 base-10

Exercise 4.2:
10101 base-2 = ??? base-10
128 64 32 16 8 4 2 1
1 0 1 0 1
16 4 1
16 + 4 + 1 = 21 base-10

Exercise 4.3:
10101010 base-2 = ??? base-10
128 64 32 16 8 4 2 1
1 0 1 0 1 0 1 0
128 32 8 2
128 + 32 + 8 + 2 = 170 base-10

Exercise 4.4:
11000000 base-2 = ??? base-10
128 64 32 16 8 4 2 1
1 1 0 0 0 0 0 0
128 64 0 0 0 0 0 0
128 + 64 = 192 base-10

Exercise 4.5:
11100000 base-2 = ??? base-10
128 64 32 16 8 4 2 1
1 1 1 0 0 0 0 0
128 64 32 0 0 0 0 0
128 + 64 + 32 = 224 base-10

Page 34 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


4.11 10110 = __________ base-10

4.12 110110 = __________ base-10

4.13 111111 = __________ base-10

4.14 1010101 = __________ base-10

4.15 11001100 = __________ base-10

4.16 11100000 = __________ base-10

4.17 11110000 = __________ base-10

4.18 11111000 = __________ base-10

4.19 11111100 = __________ base-10

4.20 11111111 = __________ base-10

4.21 10101010 = __________ base-10

4.22 00110011 = __________ base-10

4.23 00001111 = __________ base-10

4.24 10000001 = __________ base-10

4.25 11111110 = __________ base-10

4.26 11110011 = __________ base-10

4.27 11100010 = __________ base-10

4.28 01010101 = __________ base-10

4.29 11011011 = __________ base-10

4.30 10010010 = __________ base-10

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 35


15.6.5 Converting Base-10 to Any Base

It is very common for students to use the trusty expansion method to convert
numbers from base-10 to some other base. This may make sense until you look at
the result and observe what you are doing.

Suppose you want to convert the number 348 base-10 into a base-5 number. Look
what happens with the expansion method.

348 base-10 = 3 x 102 + 4 x 101 + 8 x 100


348 base-10 = 3 x 100 + 4 x 10 + 8 x 1
348 base-10 = 300 + 40 + 8 = 348

Well cleverness abounds here. You see how we can very skillfully convert the
348 number with expansion right back into 348. This is not a satisfactory result.
A different approach is necessary.

There are several different ways to convert a base-10 number to another base.

One way involves dividing the base-10 number by the desired base value again
and again until you get a quotient of 0. If you then take all of the remainders in
reverse order, you will have your answer.

The next example demonstrates converting to base-2 for simplicity. This is


followed by other examples with different bases. Other examples will follow.

You may be surprised that the expansion method is not used in reverse. That
certainly works. You can set up a table with place holder values for each base.

Page 36 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 37
Convert 50610 to hexadecimal:

Using the division


method, when we
take the remainders
in reverse order we
get 1(15)(10).
We need to do one
extra step to make
this right.

When the 10 and


15 are converted
to A and F, we can
now properly find
the answer of 1FA.

Page 38 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


5.1 324 base-10 = _____________ base-4

5.2 294 base-10 = _____________ base-5

5.3 125 base-10 = _____________ base-8

5.4 506 base-10 = ____________ base-16

5.5 45 base-10 = ____________ base-2

5.6 37 base-10 = ____________ base-2

5.7 63 base-10 = ____________ base-2

5.8 64 base-10 = ____________ base-2

5.9 100 base-10 = ____________ base-2

5.10 127 base-10 = ____________ base-2

5.11 100 base-10 = ____________ base-5

5.12 100 base-10 = ____________ base-4

5.13 100 base-10 = ____________ base-3

5.14 500 base-10 = ____________ base-16

5.15 1000 base-10 = ____________ base-16

5.16 1000 base-10 = ____________ base-8

5.17 128 base-10 = ____________ base-2

5.18 111 base-10 = ____________ base-2

5.19 1000 base-10 = ____________ base-2

5.20 1024 base-10 = ____________ base-2

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 39


15.7 The AP® Picture Labs

Back in Chapter VIII you were introduced to the Magpie Chatbot AP® Lab. It
then continued with the Elevens AP® Lab, which has been spread over many
chapters and also has not yet concluded. In fact, you have not seen the Elevens
card game at all. Patience, that is in the next chapter. In this chapter the third of
the three AP® Labs, known as the AP® Picture Labs will be presented. Unlike the
other two labs, the Picture programs will be completely contained within this
Two-Dimensional Array chapter.

The Picture Labs are very different from the other two AP® Labs. Both the AP®
Magpie Lab and the AP® Elevens Lab are single labs. Each lab may be an
interaction of multiple classes, but each lab is a single program aiming towards a
specific goal. This is not the case with this third lab and you will see it frequently
mentioned as the AP® Picture Labs (plural).

There is another important difference. Considerable effort has been used to


explain the program code of the Magpie program and the Elevens program. The
Elevens program has not yet reached its conclusion, but you are learning about
this program in stages. The point is that you are learning to understand the actual
program code that is performing the Magpie program and the Elevens program.
Learning this code is very beneficial for many different computer science
program concepts and Java program code that is part of the curriculum.

With the Picture labs you will get considerable practice in manipulating two-
dimensional arrays. Pictures are two-dimensional arrays of pixels and you will do
some interesting lab experiments and lab assignments manipulating pictures.
Along the way you will get considerable practice creating, accessing and altering
two-dimensional arrays. This is the goal of these labs and it is done in a very
fascinating environment of digital photography. It will not take long to realize that
much of the program code is very foreign looking and does not resemble anything
that you have learned earlier. No problem. Your job is to use available methods
from a variety of different classes without concern about the implementation of
these specialized graphics methods.

The Elevens Lab has gone through many chapters to help explain the code and
this code is steadily becoming more complex. With the Picture Labs there is no
initial simple version of the later complex code. You will right away use the
actual Picture Labs code.

Your job is to become familiar with the available functionality of the various
Picture Lab classes with its methods. Then you are expected to take the existing
methods and create new functionalities with digital pictures. At the end you will
have done a variety of interesting programs with digital pictures and along the
way increased your knowledge of two-dimensional arrays.

Page 40 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Before we continue let us first take a look and give proper credit to the person
who developed the AP® Picture Labs. Teaching computer science with digital
media is one of Dr. Ericson’s specialties.

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 41


Exposure Java and the AP® Labs
The AP® Computer Science Test Development
Committee has coordinated the creation of these
new AP® Labs for the College Board®.

The third AP® Lab, called the AP Picture Labs along


with its documentation, is developed by Barbara
Ericson of the Georgia Institute of Technology.

Exposure Java and its Authors Leon Schram


(father) and John Schram (son) include the three
AP® labs in this textbook, but had no part in its
development.

What has been done in Exposure CS is to present


the AP® Labs throughout the curriculum where
appropriate. The labs are not always shown
completely, but rather a smaller sequence of
incomplete versions of these labs are introduced to
help in understanding the computer science
concepts and Java code presented by each lab.

Even though, the initial lab introductions, and


various stages along the way are different from the
AP® labs presented by the College Board®, the final
stages shown in Exposure Java are exactly, like the
College Board® versions.

Page 42 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


15.7.1 AP® Picture Lab Experiment 01

Picking a Color
Graphics and computers colors are not a new topic. In many chapters you have
seen program examples with graphics displays created by Java program code. The
fundamentals of graphics commands and the fundamentals of color you know
already. What is new in this chapter is that you will be manipulating digital
graphics images that already exist. In other words, it is not your job to write Java
program code that generates some type of graphics display. Rather, you will take
existing digital pictures and manipulate them in many different ways.

In this chapter you also looked at number systems ,which was placed intentionally
prior to this segment of the chapter. Computer colors are a mix of red, green and
blue shades of different intensity. The color values range is [0..255]. Color value
255 shows the brightest color. Load ColorDemo01.java from your Experiment01
folder, shown in figure 15.19. Figure 15.19 shows the applet window graphics
output followed by the text window output of the toString Color method.

Figure 15.19

// ColorDemo01.java
// This demo shows the Red, Green and Blue color with their highest (255) intensities.

import java.awt.*;
import java.applet.*;

public class ColorDemo01 extends Applet


{
public void paint(Graphics g)
{
Color brightRed = new Color(255,0,0);
Color brightGreen = new Color(0,255,0);
Color brightBlue = new Color(0,0,255);

System.out.println("Red: " + brightRed);


System.out.println("Green: " + brightGreen);
System.out.println("Blue: " + brightBlue);

g.setColor(brightRed);
g.fillRect(50,100,200,200);
g.setColor(brightGreen);
g.fillRect(300,100,200,200);
g.setColor(brightBlue);
g.fillRect(550,100,200,200);
}
}

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 43


Figure 15.19 Continued

Art students - and perhaps people in general - may not quite understand the
computer red, green and blue set of primary colors. When paints are mixed it is
understood that the primary colors are red, blue and yellow. This is not the place
to become technical about color, but mixing paint color and mixing light colors
are not the same. Your art teacher can explain this better than I can and I have
some memory that paint colors are subtractive and computer colors are additive.
What does it all mean? It seems simple to me. In the computer lab write graphics
programs and use primary colors red, green and blue. When you arrive in the art
room and start painting, mix the primary paint colors red, blue and yellow.

It is interesting to note that RGB colors with minimal values zero, have no color
at all and become totally black. When all three RGB colors reach the maximum
color value of 255, the result is white.

Page 44 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Now load ColorDemo02.java, shown in figure 15.20. This program generates
three random integer values in the [0.255] range and displays a large square of
that color and its RGB values. Execute the program multiple times to observe
different color combination.

Figure 15.20

// ColorDemo02.java
// This color demo shows a new random color and its
// RGB values each time it is executed.

import java.awt.*;
import java.applet.*;

public class ColorDemo02 extends Applet


{
public void paint(Graphics g)
{
int rndRed = (int) (Math.random() * 255);
int rndGreen = (int) (Math.random() * 255);
int rndBlue = (int) (Math.random() * 255);
Color randomColor = new Color(rndRed,rndGreen,rndBlue);
g.setColor(randomColor);
g.fillRect(50,50,400,400);

g.setColor(Color.black);
g.setFont(new Font("Arial",Font.BOLD,48));
String colorString = "[" + rndRed + "," + rndGreen + "," + rndBlue + "]";
g.drawString(colorString,100,225);
}
}

Figure 15.20 Continued

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 45


All the files of the AP Picture programs are in one location. To simplify access
you are working with folders that only have the necessary program files available
for each individual experiment. This will mean duplication of files, but the
intention is to make the individual experiments simpler.

Load the ColorChooser.java file in your Java IDE. It is a short program and the
first one of the AP Picture Lab programs. The code is shown in figure 15.21.

Figure 15.21

import javax.swing.JColorChooser;
import javax.swing.JFrame;
import java.awt.Color;

/**
* A class to make working with a color chooser easier
* for students. It uses a JColorChooser to let the user
* pick a color and returns the chosen color object.
*
* @author Barb Ericson ericson@cc.gatech.edu
*/
public class ColorChooser
{
/**
* Method to let the user pick a color and return
* the color object.
* @return the picked color or red if no color was picked
*/
public static Color pickAColor()
{
Color color = Color.white;

// create a JFrame to be the parent of the color chooser open dialog


// if you don't do this then you may not see the dialog.
JFrame frame = new JFrame();
frame.setAlwaysOnTop(true);

// use the color chooser to pick the color


color = JColorChooser.showDialog(frame,"Pick a color",color);

return color;
}

/** Main method for testing the ColorChooser */


public static void main(String[ ] args)
{
Color pickedColor = ColorChooser.pickAColor();
System.out.println(pickedColor);
}
}

Page 46 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


The output in figure 15.22 may be somewhat different on your computer. It
depends on the Java JDK version that is installed on your computer. This version
is Java 8.0. All versions are meant to allow working with colors.

Figure 15.22

Click on the RGB tab to get the figure 15.23 screen display. You can now move
the sliders to get different color displays. Note the Color Code window that
shows the RGB color in hexadecimal or base-16 values. The Alpha value is the
degree of transparency or opaqueness. With an alpha value of 0 the image is
totally transparent and with alpha value 255 the image is totally opaque.

Figure 15.23

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 47


Use this ColorChooser program to answer the following questions:

1. What RGB combination is total black?

2. What RGB combination is total white?

3. What color do you get when all three RGB values are the same?

4. What practical use is there for the Alpha value?

5. What is the decimal color code for FFFF00?

6. What is the decimal color code for 00FFFF?

7. What is the decimal color code for FF00FF?

8. What is the decimal color code for AAAAAA?

9. What color code is orange?

10. What color code is brown?

11. What color code is pink?

12. What color code is purple?

13. What color is peach?

14. What color code is cyan?

15. What color code is magenta?

16. What color code is maroon?

17. What color code is beige?

18. What color code is olive?

19. What color code is lime green?

20. What color code is medium gray?

Page 48 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


15.7.2 AP® Picture Lab Experiment 02

Exploring a Picture
This experiment involves a lot more classes. Go to the Experiment02 folder and
then load the PictureExplorer.java file. In figure 15.24 you will only see the end
of the file where the main method is located. For this experiment there is no
concern at all with the Java code and altering any methods. Any changes you
make will only be done in the main method. Compile, then run the program and
you should see a beach picture.

Figure 15.24

/**
* Test Main. It will explore the beach
*/
public static void main( String args[])
{
Picture pix = new Picture("beach.jpg");
pix.explore();
}
}

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 49


True to its name this program lets you explore a picture. At the top you see two
windows for (x,y) coordinates of a pixel location on the picture. This can be done
two ways.

Right now go ahead and click roughly in the middle of the picture. Figure 15.25 is
a part of the picture to help you see the very small, yellow cross of the mouse-
click location. You will also see that this is coordinate (332,224). Don't get
confused. It is natural to display a pixel as an (x,y) coordinate. However, when we
work with pictures as a two-dimensional array they are handled in row-col order.
There is more information and at the (332,224) location the RGB values are
[125,148,142], which is displayed along with a small square showing that color.

It is also possible to reverse the operation. This time don't click on the picture, but
click on the arrows of the coordinate values. As you alter those values, you will
see the yellow pixel cross move.

Figure 15.25

Page 50 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Use this PictureExplorer program to answer the following questions:

1. Find the (x,y) coordinates of the image at the top-left corner.

2. Find the (x,y) coordinates of the image at the top-right corner.

3. Find the (x,y) coordinates of the image at the bottom-left corner.

4. Find the (x,y) coordinates of the image at the bottom-right corner.

5. What is the width of the image?

6. What is the height of the image?

7. Use the Zoom tool in the top-left corner.


Zoom in to 150% and stretch the image window to make the picture fit.
Is the height and width now proportionally larger than before?

8. Zoom all the way to 500%. The picture now appears fuzzy, out of focus
and you can see individual large, square pixels. This is a process called
pixelation when pixels become large enough to look like small squares.

9. Go to the very bottom of the PictureExplorer.java file. Change the


image name in the main method to "astrid1.jpg". Compile and run the
altered program. Click anywhere on the picture. What do you observe?

10. Replace the explore method with the show method.


Re-compile and re-run. Has anything changed?

11. There is a scale method that can alter the picture size. Construct a new
Picture object using the scale method to get 25% of the picture and
change the program code in the main method of the PictureExplorer
class as shown below:
Picture pix1 = new Picture("astrid1.jpg");
Picture pix2 = pix1.scale(0.25,0.25);
pix2.show();
pix2.write("astrid2.jpg");
You will observe a smaller picture courtesy of the show method.
What does the write method do?

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 51


15.7.3 AP® Picture Lab Experiment 03

Using the Javadoc Comments

Take a look at the Java program code in figure 15.26. The code has lots of
documentation. In one of the early chapters you learned about documentation for
single lines, such as . . .
// This is a single line comment.

You have also seen multi-line comments, like . . .


/*
This is line 1.
This is line 2.
This is line 3.
*/

Java also has a third type of comment that is visible in the code below. It looks
like an odd type of multi-line comment, but it is more than a comment in the
program code. It has some special properties.

Figure 15.26

Page 52 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Java has a special program, called Javadoc that can take one or more classes and
creates web page documentation for these classes. This web-based documentation
is available to explain standard Java interfaces, classes and methods, but it can
also be used to create such documentation for user-defined classes.

We are in the middle of the AP Picture Labs and there are many programs to look
at, experiments to perform and also some lab assignments to complete. All this
work revolves around manipulating digital pictures, which are essentially 2D
arrays of pixels. Manipulating these pictures is done with many classes and within
these many classes are even more methods. This can get quite confusing.
Furthermore, you are not really expected to learn the program code of these many
methods, but you do need to know how to use the methods. This requires the
following information.

Using a method requires knowledge of the

 Class identifier
 Method identifier
 Method description (what does it do)
 Method parameter requirements

This information is known at the API or Application Program Interface. It exists


for the entire Java standard language and it also exists with many non-standard
programs that have created this documentation to provide a handy reference of the
code that is used.

The first two experiments with the AP Picture Labs were done without this
information. The reality is that for Experiment01 and Experiment02 you strictly
used existing programs. You were looking at different colors and you were
exploring a picture. In other words, you were not at the level of a programmer.

Now the experiments change. You are expected to create new methods in existing
classes to manipulate pictures. Creating these methods requires the use of many
specialized methods that already exist. Making sense of all these classes and
methods is the web-based documentation that exists for the AP Picture Labs. First
find the Experiment03 folder, shown in figure 15.27 and then open the lone
PicturesJavaDoc folder shown in figure 15.28. The web-page contents of the
PicturesJavaDoc folder are shown incompletely. Look for the index.html file.

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 53


Figure 15.27 Figure 15.28

All the files in PicturesJavaDoc are web pages of the classes in the AP Picture
Labs. They do not contain the program code, but specific documentation about the
classes and methods that the programmer wanted to be easily visible. To see this
documentation double-click on index.html.

Figure 15.29 shows the initial view of the Web-Based documentation that was
created for AP Picture Labs. In the left window 11 classes are displayed and 1
interface. The interface, DigitalPicture, is italicized. The main window shows the
current class or interface that is chosen. In this case it is ColorChooser.

Page 54 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


You are going to look at the Java Web-Based Documentation two ways. First, you
want to read the description of the classes to get an idea what their purposes are.
Second, you see information about superclasses and subclasses, which help you to
identify the hierarchy of the classes.

Much can be said about this documentation, but right now scroll up and down.
Check out the details of the constructor, the data fields and the methods.

Figure 15.29

Figure 15.30 shows the Picture class. This class will become important in future
experiments. Do the same thing. Scroll, check out some method and see what
information you can find.

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 55


Figure 15.30

The number of classes that are part of the AP Pictures Labs are numerous and the
methods are even greater in number. Don't worry about memorizing all the
details. Your first job is to get an overview what is available. Ten classes and one
interface follow.

A snapshot of the web page is shown and it shows that part that indicates the
name of the class, a diagram of the class hierarchy and its subclasses. What does
hierarchy mean? It is a pyramid structure with a superclass and its subclasses. In
the Catholic Church the Pope is at the top of the hierarchy, followed by the
Bishops who each are in charge of a Diocese, which in turn consists of parishes
that are manned by Priests.

Each short snapshot also provides a short description of the class. Again don't try
to remember. Knowing that there exists a summary in this chapter helps and you
will find that the actual web pages are available with various Lab Experiments
where the information is needed.

Page 56 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Summary of AP® Picture Lab Classes

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 57


These two classes will not be addressed in this chapter. They are designed to
teach and demonstrate Java static arrays. What is shown by these classes has
already been taught in the earlier section of this chapter. For this reasons the files
are not included with the experiments of the AP Pictures Labs.

Page 58 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 59
Page 60 Exposure Computer Science 2016 for AP®CS (A) 07-22-16
Group Exercises for 3 or 4 People
With your groups analyze the 11 classes and interface.

Create a hierarchy diagram.


This diagram shows superclasses, subclasses and
implementing classes.

There are also independent classes which have no interaction


with any of the other classes. Identify them.

It is not necessary to remember all the many methods, nor is it


necessary to even remember all the classes. What is
necessary is that you can quickly search through the provided
JavaDoc web pages of the AP® Picture labs and find the class
information and the method information that you require.

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 61


15.7.4 AP® Picture Lab Experiment 04

Remove All Blue from a Colored Picture


This is the first of many modifying pictures experiments. Initially you will do the
experiments by the numbers. These are experiments that explain exactly what
needs to be done and provide the sequence of the steps, which are necessary to
complete the experiment. This first experiment teaches you how to manipulate
colors in a picture. In this experiment all the blue colors will be removed.

Step 1

Load the PictureTester.java file.


Scroll to the bottom of the file and look for the main method.
You will see many method calls that are all commented out.
Only testZeroBlue is called.

Step 2

Find method testZeroBlue, which creates a Picture object with "beach.jpg".


Method explore is called twice before and after blue removal.
The zeroBlue method is called to remove all blue color from the image.

public static void testZeroBlue()


{
Picture beach = new Picture("beach.jpg");
beach.explore();
beach.zeroBlue();
beach.explore();
}

Compile and execute the program.


You should see two identical pictures - on top of each other - shown below.

Page 62 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Step 3

Load the Picture.java file and find the zeroBlue method.


Examine the zeroBlue method.
For this experiment the PictureTester class and the Picture class have been altered.
Many methods, not necessary for this experiment were removed, for simplicity.

Step 4

Right now method zeroBlue is not very functional looking like:


public void zeroBlue()
{

That explains why the two beach pictures were identical.

Step 5

Method zeroBlue first must create a pixels array with method getPixels2D.
You will not find getPixels2D in the Picture class.
Look in the superclass of Picture, SimplePicture; you will find it there.
Many other methods are found in SimplePicture class as well.

The for..each loop is used to access each individual Pixel object of the array.
You will also need to examine the Pixel class, which will be used frequently.
The setBlue method of the Pixel class is used to set the blue value to 0 for every pixel.

Use the following code and write it into the Return to the PictureTester class.
zeroBlue method of the Picture class. Re-compile and re-execute the program
and now the second beach picture will
public void zeroBlue() have all the blue removed from every
{ pixel and looks like the picture below.
Pixel[][] pixels =
this.getPixels2D();
for (Pixel[] rowArray: pixels)
{
for (Pixel pixelObj:rowArray)
{
pixelObj.setBlue(0);
}
}
}

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 63


15.7.5 AP® Picture Lab Experiment 05

Change a Colored Picture to Black & White


This next picture-modifying experiment is more challenging. The last experiment
focused on one color and changed all values of the color blue to zero. In the next
experiment the object is to take a colored picture and change it so that it looks like
the same picture in shades of gray.

Step 1

Load the PictureTester.java file.


Scroll to the bottom of the file and look for the main method.
You will see many method calls that are all commented out.
Uncomment the testGrayScale method by removing the two comment slashes.

Step 2

Find method testGrayScale()


Right now the method has no program statements.
Write in the program statements that are shown below.

Add method testGrayScale to the PictureTester class at the bottom above main.

public static void testGrayScale()


{
Picture pix = new Picture("beach.jpg");
pix.explore();
pix.grayScale();
pix.explore();
}

Step 3

The PictureTester class is only concerned with creating Picture objects and testing
them with some new method. All that has been done so far is call method
testGrayScale. In that method a new Picture object is constructed.

The object pix then calls method explore, which displays the image.
The explore method already exists in the PictureExplorer class.
Much of what you will do involves knowing what exists - and can be used - and knowing
what does not exist and must be created.

The grayScale method does not exist and needs to be created.


Why must it be created in the Picture class and not the PictureTester class?

Page 64 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Step 4

Black & White pictures are not pictures with groups of pixels that are black or white.
These pictures display pixels with shades of gray. There are 256 shades of gray. Each
gray shade is created with the same values for red, green and blue. (0,0,0) is totally
black. (100,100,100) is a medium shade of gray.

Here are steps necessary to turn a colored picture into a black & white picture:

 Create a two-dimensional array pixels object. Pixel objects store color values.
 Access each pixel in the array and get the three color values.
 Add up the three color values of the pixel.
 Divide this color sum by three to get the average color, which is the gray value.
 Assign the equivalent gray color to the pixel.

Step 5

In your groups create the grayScale method. Do not be afraid to use trial & error. It is
not necessary to have the complete and correct solution in your head before you start.
We learn a lot from incorrect program code.

The first picture below is the beach.jpg with the original color picture.
The second picture shows the converted black and white version of beach.jpg.
When you execute the program, the pictures will be on top of each other.
You can drag them besides each other to make comparisons.

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 65


Step 5 Continued

15.7.6 AP® Picture Lab Experiment 06

Mirror Images
You saw with the grayScale experiment how a colored image can be altered to a
black & white picture. Specialized methods were used to access individual pixels
and then access and alter pixel color values. None of this is a possibility without
knowledge of manipulating two-dimensional arrays. A digital image is a two-
dimensional array of individual pixels and each pixel store a red, green and blue
value to create a very large variety of colors. At the conclusion of this chapter you
will do a lab assignment that involves altering digital pictures.

Page 66 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Step 1

Observe the pictures below which are taken from your future lab assignment. In this
experiment you will write various methods that manipulate two-dimensional, number
arrays. You will find that the algorithms you create to alter the arrays will follow the
same logic when you start to alter the pictures.

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 67


Step 2

Open the Experiment06 folder and load the Mirror01st.java. The file is shown below
and it is the first of five array-altering experiments. Each one of the five programs will
create a two-dimensional, static int array with an initializer list. Method displayMatrix
is already finished. You and your partner need to write the mirror method.

Page 68 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Step 3

Your objective is to complete the program by writing method mirror. The end result is
a display of two matrixes. The top matrix is the original array created with the initializer
list. The second matrix is the appearance after executing your mirror method.

Step 4

Complete method upsideDown, which alters the two-dimensional integer matrix


from the original display, shown at the top, to the new storage, shown at the bottom.

, whiuch

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 69


Step 5

Complete method mirrorHorizontal, which alters the two-dimensional integer matrix


from the original display, shown at the top, to the new storage, shown at the bottom.

Step 6

Complete method mirrorVertical, which alters the two-dimensional integer matrix


from the original display, shown at the top, to the new storage, shown at the bottom.

Page 70 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Step 7

Complete method mirrorDiagonal, which alters the two-dimensional integer matrix


from the original display, shown at the top, to the new storage, shown at the bottom.

Step 8

Little was stated about array size in the previous five experiements. All the matrixes
were square-sized. That is required for the mirrorDiagonal method, but the others
only require a rectangular matrix.

Consider odd-sized and even sized matrixes. If your solutions work well for the
provided matrix size, will it work also when you change the size?

Perhaps your teacher already had you change sizes with each experiment, but if you
completed each experiment successfully, with the provided matrix, try it again. Change
any even-sized to odd-sized and change the odd-sized to even-sized and see if you
methods still perform correctly.

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 71


15.8 Summary

Two-dimensional arrays, or matrixes, are all around you. You see it in your
classroom with the desks. You see it at concerts and football stadiums. You see it
when you get on an airplane and check your boarding pass for your seat. You see
it when you open a spreadsheet and look at many rows and many columns of data.
Computers simulate life and the two-dimensional array in Java simulates many of
the common aspects of your daily routine.

Dynamic two-dimensional arrays are possible with the ArrayList class, but they
are not so commonly used. The old-fashioned, index brackets, static arrays is the
first choice for most programmers.

Declaring a static 2D array requires two sets of square brackets, like:

int[ ][ ] square = new int[5][5];

Displaying a 2D array can be done with index access or without index


access using the for. . each loop. The for . . each requires access to
every array member and is read . . only.

for (int row = 0; row < matrix.length; row++)


{
for (int col = 0; col < matrix[0].length; col++)
System.out.print(matrix[row][col] + " ");
System.out.println();
}

for (int[ ] row : matrix)


{
for (int number : row)
System.out.print(number + " ");
System.out.println();
}

Note that matrix.length is the number of rows in a 2D Array


and matrix[0].length is the number of columns in 2D Array.
This also shows that a 2D array is in fact a 1D array or one or
more 1D Arrays.

Page 72 Exposure Computer Science 2016 for AP®CS (A) 07-22-16


Computers store information and perform calculations in the binary machine code
of base-2. Since base-2 is tedious, and since there every base-16 digit is equal to a
four-digit base-2 number, memory addresses use the base-16 hexadecimal code.
Base-16 is also used with RGB (Red, Green Blue) graphics color values.

Counting in all number systems is based on starting at zero and counting to one
less than the base, which is the largest single digit. After the largest single digit is
reached, a system is used where by each digit has a place-holder value that
increases by the value of the base. For instance in base-10 we have the following
place holders that are single digits with values that are powers of the base.

1 2 3 4 5 6 7 8
10,000,000 1,000,000 100,000 10,000 1000 100 10 1

In base there are only two digits, 1 and 0. The place holder values now increase as
a power of the base 2.

1 1 1 1 1 1 1 1
128 64 32 16 8 4 2 1

When a number has a base larger than 10, it is necessary to create new single
digit. In the case of base-16, letter are used.

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
F E D C B A 9 8 7 6 5 4 3 2 1 0

Digital images are two-dimensional arrays of pixels. Each pixel stores the red,
green and blue values of the pixel. Knowledge of various methods that get the
pixel colors and sets the pixels colors can be combined with 2D Array
manipulations to alter images.

For instance the color gray is a mix of three identical red, green and blue values.
Color (0,0,0) is the darkest black. Color (255,255,255) is pure white and the color
(100,100,100) is a shade of gray. Program code can be written to access the color
values of each pixel in a digital image. If the average color value is switched to a
shade of gray for each pixel in a color picture, the image become black&white
picture.

Pixel values can also be copied to other sections of the image to create mirror
images. In one technique of a symmetrical building, like a temple, an old picture
with a roof, broken on one side can be digitally repaired. The whole, left side, of
the roof can be mirror copied unto the broken, right side of the roof to create a
picture that resembles the original building.

Chapter XV Two-Dimensional Arrays and the AP Picture Labs Page 73


This is the temple as it appears today. The roof is pretty good on side, but
destroyed on the other side. Doing a simple mirror image of half the picture is not
sufficient. In such a case it will alter the placement of the bushes in front of the
temple.

This altered picture gives an impression of the original temple. The mirror image
is strictly local to the roof only. Note how the bushes are the same in both
pictures.

Page 74 Exposure Computer Science 2016 for AP®CS (A) 07-22-16

Você também pode gostar