Professional Documents
Culture Documents
Lec 5
Lec 5
ARRAYS
Array is a data structure that represents a collection of the same types of data as
shown in Figure 5.1.
myList reference
myList[0] 5.6
myList[1] 4.5
myList[4] 4
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34
myList[7] 45.45
myList[8] 99.993
myList[9] 11123
Figure 5.1 The array myList has ten elements of double type and int
indices from 0 to 9.
Caution
Using the shorthand notation, you have to declare, create, and initialize the array
all in one statement. Splitting it would cause a syntax error. For example, the
following is wrong:
double[] myList;
myList = {1.9, 2.9, 3.4, 3.5};
You can also create and initialize an array using the following syntax:
new dataType[]{literal0, literal1, …,literalk};
For example,
double[] myList = {1, 2, 3};
// sometimes later …
myList = new double[]{1.9, 2.9, 3.4, 3.5}
When processing array elements, you will often use a for loop. Here are the
reasons:
• All of the elements in an array are of the same type.
• Since the size of the array is known, it is natural to use a for loop.
Enhanced forLoop
JDK 1.5 introduced a new for loop that enables you to traverse the complete array
sequentially without using an index variable. For example, the following code
displays all elements in the array myList:
for (double value: myList)
System.out.println(value);
In general, the syntax is
for (elementType value: arrayRefVar) {
// Process the value
}
You still have to use an index variable if you wish to traverse the array in a
different order or change the elements in the array.
Example 5.1: Testing Arrays
Problem
Write a program that receives 6 numbers from the keyboard, finds the largest
number and counts the occurrence of the largest number entered from the
keyboard. Suppose you entered 3, 5, 2, 5, 5, and 5, the largest number is 5 and its
occurrence count is 4.
Solution
The source code for the program is shown below:
import javax.swing.JOptionPane;
You can trace the value of array elements in the debugger as shown in Figure 5.2.
Example 5.2 Assigning Grades
Problem
Write a program to read student scores (int), get the best score, and then assign
grades based on the following scheme:
• Grade is A if score is >= best–10;
• Grade is B if score is >= best–20;
• Grade is C if score is >= best–30;
• Grade is D if score is >= best–40;
• Grade is F otherwise.
The following code gives the solution to the problem. The output of a sample run
of the program is shown in Figure 5.3.
The Program:
import javax.swing.JOptionPane;
list1 list1
Contents Contents
of list1 of list1
list2 list2
Contents Contents
of list2 of list2
Garbage
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[]targetArray = new int[sourceArray.length];
The statement
printArray(new int[]{3, 1, 2, 6, 4, 2});
creates an array using the following syntax:
new dataType[]{literal0, literal1, ..., literalk};
There is no explicit reference variable for the array. Such array is called an
anonymous array.
5.6.2 Pass By Value
Java uses pass by value to pass parameters to a method. There are important
differences between passing a value of variables of primitive data types and
passing arrays.
• For a parameter of a primitive type value, the actual value is passed. Changing the
value of the local parameter inside the method does not affect the value of the
variable outside the method.
• For a parameter of an array type, the value of the parameter contains a reference
to an array; this reference is passed to the method. Any changes to the array that
occur inside the method body will affect the original array that was passed as the
argument.
Simple Example
public class Test {
public static void main(String[] args) {
int x = 1; // x represents an int value
int[] y = new int[10]; /* y represents an array of
int values */
When invoking m(x, y), the values of x and y are passed to number and numbers.
Since y contains the reference value to the array, numbers now contains the same
reference value to the same array.
5.6.4 Heap
The JVM stores the array in an area of memory, called heap, which is used for
dynamic memory allocation where blocks of memory are allocated and freed in
an arbitrary order.
Problem:
Write a program that does the following:
1. Generate 100 lowercase letters randomly and assign them to an array of
characters.
2. Count the occurrence of each letter in the array.
The program:
public class CountLettersInArray {
/** Main method */
public static void main(String args[]) {
// Declare and create an array
char[] chars = createArray();
// Display counts
System.out.println();
System.out.println("The occurrences of each letter
are:");
displayCounts(counts);
}
return counts;
}
You can create a two-dimensional array of 10 by 10 int values and assign its
reference to variable as follows:
/* Create array and assign its reference to variable */
refVar = new dataType[10][10];
/* Combine declaration and creation in one statement */
dataType[][] refVar = new dataType[10][10];
// Alternative syntax
dataType refVar[][] = new dataType[10][10];
1 1 1 4 5 6
2 2 7 2 7 8 9
3 3 3 10 11 12
4 4 int[][] array = {
{1, 2, 3},
matrix = new int[5][5]; {4, 5, 6},
matrix[2][1] = 7; {7, 8, 9},
{10, 11, 12}
matrix.length? 5 };
matrix[0].length? 5 array.length? 4
array[0].length? 3
x[2]
x[2][0] x[2][1] x[2][2] x[2][3] x[2].length is 4
x.length is 3
matrix.length is 5
matrix[0].length is 5
matrix[1].length is 4
matrix[2].length is 3
matrix[3].length is 2
matrix[4].length is 1
int[][] triangleArray = { 1 2 3 4 5
{1, 2, 3, 4, 5},
{2, 3, 4, 5}, 1 2 3 4
{3, 4, 5},
{4, 5}, 1 2 3
{5}
}; 1 2
1 2
If you don't know the values in a ragged array in advance, you can create a ragged
array using the syntax that follows:
int[][] triangleArray = new int[5][];
triangleArray[0] = new int[5];
triangleArray[1] = new int[4];
triangleArray[2] = new int[3];
triangleArray[3] = new int[2];
triangleArray[4] = new int[1];
int x[][]={{1,2,3},{1,2},{1}};
sum(x);
public static int sum(int[][]x){
int sum=0;
for(int i=0;i<x.length;i++)
for(int j=0;j<x[0].length;j++)
sum+=x[i][j];
return sum;
}
Example 5.10 Adding and multiplying two Matrices
Problem:
Write a program that uses two-dimensional arrays to represent two matrices. The
program then adds and multiplies the two matrices.
Solution:
Assume both arrays are 5 by 5 with int type elements. The program is given below.
The output of the program is shown in Figure 5.12.
The program:
// TestMatrixOperation.java add and multiply two
matrices
public class TestMatrixOperation {
/** Main method */
public static void main(String[] args) {
// Create two matrices as two dimensional arrays
int[][] matrix1 = new int[5][5];
int[][] matrix2 = new int[5][5];
// assign random values to matrix1 and matrix2
for(int i=0; i<matrix1.length; i++)
for(int j=0; j<matrix1[i].length; j++) {
matrix1[i][j] = (int)(Math.random() * 10);
matrix2[i][j] = (int)(Math.random() * 10);
}
// add two matrices and print the result
int[][] resultMatrix = addMatrix(matrix1, matrix2);
System.out.println("The addition of the matrices is
");
printResult(matrix1, matrix2, resultMatrix, '+');
(x, y)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 250);
frame.setVisible(true);
}
}
The drawArc method draws an arc based on an oval with specified angles.
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
publicclass DrawArcs extends JFrame {
public DrawArcs() {
setTitle("DrawArcs");
getContentPane().add(new ArcsPanel());
}
/** Main method */
publicstaticvoid main(String[] args) {
DrawArcs frame = new DrawArcs();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 300);
frame.setVisible(true);
}
}
// The class for drawing arcs on a panel
class ArcsPanel extends JPanel {
// Draw four blazes of a fan
protectedvoid paintComponent(Graphics g) {
super.paintComponent(g);
(x[0], y[0])
(x[1], y[1])
(x[3], y[3])
(x[4], y[4])
(x[2], y[2])
g.drawPolyline(x, y, x.length);
(x[0], y[0])
(x[1], y[1])
(x[3], y[3])
(x[4], y[4])
(x[2], y[2])
Sheet 5
6) Write a program that will read ten integers and display them in reverse order.
7) Write a method that sums all the integers in the major diagonal in a matrix of
integers. Use {{1,2,4,5}, {6,7,8,9}, {10,11,12,13}, {14,15,16,17}} to test the
method.
8) Write a program that reads student scores, gets the best score, and then assigns
grades based on the following scheme: Grade is A if score is best; Grade is
B if score is best ; Grade is C if score is best ; Grade is D if score is best ;
Grade is F otherwise. The program prompts the user to enter the total number
of students, then prompts the user to enter all of the scores, and concludes by
displaying the grades. Here is a sample run:
9) Write two overloaded methods that return the average of an array with the
following headers:
public static intaverage(int[] array)
public static doubleaverage(double[] array)
Write a test program that prompts the user to enter ten double values, invokes this
method, and displays the average value.
10) Write a method that returns the index of the smallest element in an array of
integers. If the number of such elements is greater than 1, return the smallest
index.
11) Write a method that returns the sum of all the elements in a specified column
in a matrix using the following header: public static
doublesumColumn(double[][] m, intcolumnIndex) Write a test program that
reads a 3-by-4 matrix and displays the sum of each column.
12)creating jframe to draw rainbow.