KING ABDULAZIZ UNIVERSITY
Faculty of Computing & Information Technology
Department of Computer Science
Lab Manual
CPCS203
Programming II
(Object-oriented)
1432/1433H
Lab - 8
Learning Procedure
1)
Stage J (Journey inside-out the concept)
2)
Stage a1 (apply the learned)
3)
Stage v (verify the accuracy)
4)
Stage a2 (assess your work)
Term I
2011
Lab-8: Arrays
Laboratory 8:
Statement Purpose:
This lab will give you practical using of Arrays in java.
Activity Outcomes:
This lab teaches you the following topics:
Manipulate a collection of data values, using an array.
Declare and use an array of primitive data types in writing a program.
Declare and use an array of objects in writing a program
Define a method that accepts an array as its parameter and a method
that returns an array
Describe how a two-dimensional array is implemented as an array of
arrays
Instructor Note:
As pre-lab activity, read Chapter 10 from the book (An Introduction to ObjectOriented Programming with Java, 4th Edition by C. THOMAS WU (Book’s
website www.mhhe.com/wu), and also as given by your theory instructor.
Names
I.D.
1. .……………..……………………………….
………………………………
2. ..……………………………………………..
………………………………
3. .……………………………………………...
………………………………
4. .……………………………………………..
..…………………………….
CPCS203 – The Lab Note
Lab-8
1
Term I
2011
Lab-8: Arrays
1) Stage J (Journey)
Introduction
Single-dimensional arrays: is a container object that holds a fixed number of
values of a single type. The length of an array is established when the array is
created. After creation, its length is fixed.
Example: An array of ten elements
Each item in an array is called an element, and each element is accessed by its
numerical index. As shown in the above illustration, numbering begins with 0.
The 9th element, for example, would therefore be accessed at index 8.
Multi-dimensional arrays: are usually represented in a row-column approach
on paper, and the terms "rows" and "columns" are used in computing.
Declare a 2-dimensional array as follows:
int[][] a2; // Declares, but doesn't allocate, 2-dim array.
Allocation:
As with all arrays, the new keyword must be used to allocate memory for an
array. For example
int[][] a2 = new int[10][5];
This allocates an int array with 10 rows and 5 columns.
Processing 2-dimensional arrays:
Often 2-dimensional arrays are processed with nested for loops. Notice in the
following example how the rows are handled as separate objects. For example,
int[][] a2 = new int[10][5];
// print array in rectangular form
for (int r=0; r<a2.length; r++) {
for (int c=0; c<a2[r].length; c++) {
System.out.print(" " + a2[r][c]);
}
System.out.println("");
CPCS203 – The Lab Note
Lab-8
2
Term I
2011
Lab-8: Arrays
}
2) Stage a1 (apply)
Lab Activities:
Activity 1:
Declaring and Creating Arrays:
You can declare and create an array by using the following syntax:
data type
[ ] arrayname = new data type[size of array]
Where data type may be int, float, long, double, string etc.
And size of array is the size (No of data you want to store).
Processing Arrays:
Here are some examples of processing arrays:
1. (Initializing arrays with random values) The following loop initializes the
array myList with random values between 0.0 and 99.0:
for (int i = 0; i < myList.length; i++) {
myList[i] = Math.random() * 100;
}
2. (Printing arrays) To print an array, you have to print each element in the
array using a loop like the one shown below.
for (int i = 0; i < myList.length; i++) {
CPCS203 – The Lab Note
Lab-8
3
Term I
2011
Lab-8: Arrays
System.out.print(myList[i] + " ");
}
3. (Summing all elements) Use a variable named total to store the sum.
Initially total is 0. Add each element in the array to total, using a loop like
this:
double total = 0; for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
Example 1.1: A program in java to first read the numbers and store them in an
array, then find the largest number in the array, and finally count the
occurrences of the largest number in the array.
import javax.swing.JOptionPane;
public class TestArray {
/** Main method */
public static void main(String[] args) {
final int TOTALNUMBERS = 6;
int[] numbers = new int[TOTALNUMBERS];
// Read all numbers
for (int i = 0; i < numbers.length; i++) {
String numString = JOptionPane.showInputDialog( "Enter
a number:");
// Convert string into integer
numbers[i] = Integer.parseInt(numString);
}
// Find the largest
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (max < numbers[i])
max = numbers[i];
}
// Find the occurrence of the largest number
int count = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == max) count++;
}
// Prepare the result
String output = "The array is ";
for (int i = 0; i < numbers.length; i++) {
output += numbers[i] + " ";
}
output += "\nThe largest number is " + max;
output += "\nThe occurrence count of the largest number "
+ "is " + count;
// Display the result
JOptionPane.showMessageDialog(null, output);
} }
CPCS203 – The Lab Note
Lab-8
4
Term I
2011
Lab-8: Arrays
Task 1.1: trace out the above code and write the excepted output?
Example 1.2:
public class Demo {
public static void main (String [] args) {
int [] a;
a = new int[4];
a[0] = 3;
for (int i = 1; i < 4; i++)
a[i] = a[0];
a[1] = 6;
for (int i = 0; i < 4; i++)
System.out.println(a[i]);
}
}
Activity 2:
How to create arrays of objects:
It is possible to create arrays of objects. These may have one or multiple
dimensions. To create follow below steps.
1. Declare an array of object.
2. Allocate memory for the array elements
Syntax to create Arrays of Objects
className
ObjectName[ ] = new className[size];
className is a name of class for which you want to create array of object.
ObjectName is a Object name given to array of object.
Note: Provide integer value in place of size to define size of number of
elements in array of object.
Example 2.1: Demonstrate the use of arrays of the objects
class Employee
{
private String name;
protected float billingRate;
public Employee(String name, float billingRate)
{
this.name = name;
this.billingRate = billingRate;
CPCS203 – The Lab Note
Lab-8
5
Term I
2011
Lab-8: Arrays
}
public float CalculateCharge(float hours)
{
return(hours * billingRate);
}
public String TypeName()
{
return("Employee");
}
}
public class TestEmployee {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Employee[]
earray = new Employee[2];
earray[0] = new Employee("A", 15.50F);
earray[1] = new Employee("B", 40F);
System.out.println("{0} charge = {1}" +
earray[0].TypeName()+"\t"+ earray[0].CalculateCharge(2F));
System.out.println("{0} charge = {1}"+
earray[1].TypeName()+"\t"+earray[1].CalculateCharge(0.75F));
}
}
Activity 3:
Passing Arrays to Methods:
To pass an array argument to a method, specify the name of the array without
any brackets. For example, if array hourlyTemperatures is declared as
double hourlyTemperatures[] = new double[ 24 ];
then the method call
modifyArray( hourlyTemperatures );
Example 3.1: Example showing Passing Arrays to Methods
1. Create a Main class and name it as PassArray.
2. Declare and create array of size ten integer.
3. Create object of Scanner class
CPCS203 – The Lab Note
Lab-8
6
Term I
2011
4.
5.
6.
7.
Lab-8: Arrays
Allow user to enter array data.
Print the array
Call the Max method to display Maximum number among the given array.
Copy the max method as it is outside the main() method.
public static int max(int[] t) {
//1. Assign the first (or any) array element to the variable
that will hold //the maximum value.
// Loop through the remaining array elements, starting at the
second //element (subscript 1).
//When a larger value is found, that becomes the new maximum.
// ============max
int maximum = t[0];
// start with the first value
for (int i=1; i<t.length; i++) {
if (t[i] > maximum) {
maximum = t[i];
// new maximum
}
}
return maximum;
}//end method max
Example 3.2: To find the Median of an array:
This method computes the median (middle) value of an array. The array must
be sorted before calling this method. It returns the middle element, or the
average of the two middle elements if there are an even number of elements.
public static double median(double[] m) {
int middle = m.length/2; // subscript of middle element
if (m.length%2 == 1) {
// Odd number of elements -- return the middle one.
return m[middle];
} else {
// Even number -- return average of middle two
// Must cast the numbers to double before dividing.
return (m[middle-1] + m[middle]) / 2.0;
}
}//end method median
Task 3.1:
Create a Main class and name it as PassArraymedian.
1.
2.
3.
4.
Declare and create array of size ten integers.
Create object of Scanner class
Allow user to enter array data.
Print the array
5. Call the median method to display median number among the given array.
CPCS203 – The Lab Note
Lab-8
7
Term I
2011
Lab-8: Arrays
Example 3.3: The example contains two methods for swapping elements in an
array. The first method, named swap, fails to swap two int arguments. The
second method, named swapFirst-TwoInArray, successfully swaps the first two
elements in the array argument
public class TestPassArray {
/** Main method */
public static void main(String[] args) {
int[] a = {1, 2};
// Swap elements using the swap method
System.out.println("Before invoking swap");
System.out.println("array is {" + a[0] + ", " + a[1] +
"}");
swap(a[0], a[1]);
System.out.println("After invoking swap");
System.out.println("array is {" + a[0] + ", " + a[1] +
"}");
// Swap elements using the swapFirstTwoInArray method
System.out.println("Before invoking
swapFirstTwoInArray");
System.out.println("array is {" + a[0] + ", " + a[1] +
"}");
swapFirstTwoInArray(a);
System.out.println("After invoking swapFirstTwoInArray");
System.out.println("array is {" + a[0] + ", " + a[1] +
"}");
}
/** Swap two variables */
public static void swap(int n1, int n2) {
int temp = n1;
n1 = n2;
n2 = temp;
}
/** Swap the first two elements in the array */
public static void swapFirstTwoInArray(int[] array) {
int temp = array[0];
array[0] = array[1];
array[1] = temp;
}
}
Activity 4:
Using 2D-array:
Example7: The Rainfall class shows how we can test our array algorithms. It
creates the rainfall array in the main () method. It then initializes the array and
CPCS203 – The Lab Note
Lab-8
8
Term I
2011
Lab-8: Arrays
prints out average daily rainfall and average daily rainfall for the month of
March. However, note that we have made a slight modification to the
initRain() method. Instead of just assigning 0 to each element, we assign a
random value between 0 and 2.0:
rain[month][day] = Math.random() * 2.0;
Note: The Math.random() method can be used to generate numeric test data
when large amounts of data are required. The data can be scaled to fit within
the expected range of the actual data.
public class Rainfall {
/**
* Initializes the rainfall array
* @ param rain is a 2D-array of rainfalls
* Pre: rain is non null
* Post: rain[x][y] == 0 for all x,y in the array
* Note that the loops use unit indexing.
*/
public void initRain(double rain[][]) {
for (int month = 1; month < rain.length; month++)
for (int day = 1; day < rain[month].length; day++)
rain[month][day] = Math.random() * 2.0; // Random rainfall
} // initRain()
/**
* Computes average daily rainfall for a year of rainfall data
* @ param rain is a 2D-array of rainfalls
* @ return The sum of rain[x][y] / 356
* Pre: rain is non null
* Post: The sum of rain / 365 is calculated
* Note that the loops are unit indexed
*/
public double avgDailyRain(double rain[][]) {
double total = 0;
for (int month = 1; month < rain.length; month++)
for (int day = 1; day < rain[month].length; day++)
total += rain[month][day];
return total/365;
} // avgDailyRain()
/**
* Computes average daily rainfall for a given month containing nDays
* @ param monthRain is a 1D-array of rainfalls
* @ param nDays is the number of days in monthRain
* @ return The sum of monthRain / nDays
* Pre: 1 <= nDays <= 31
* Post: The sum of monthRain / nDays is calculated
CPCS203 – The Lab Note
Lab-8
9
Term I
2011
Lab-8: Arrays
*/
public double avgRainForMonth(double monthRain[], int nDays) {
double total = 0;
for (int day = 1; day < monthRain.length; day++)
total = total + monthRain[day];
return total/nDays;
} // avgRainForMonth()
public static void main(String args[]) {
double rainfall[][] = new double[13][32];
Rainfall data = new Rainfall();
data.initRain(rainfall);
System.out.println("The average daily rainfall = "
+ data.avgDailyRain(rainfall));
System.out.println("The average daily rainfall for March = "
+ data.avgRainForMonth(rainfall[3],31));
} // main()
} // Rainfall class
3) Stage v (verify)
Home Exercises:
1. Indicate true or false for the following statements:
Every element in an array has the same type.
The array size is fixed after it is declared.
The array size is fixed after it is created.
The elements in an array must be of primitive data type.
2. Which of the following statements are valid array declarations?
int i = new int(30);
double d[] = new double[30];
char[] r = new char(1..30);
int i[] = (3, 4, 3, 2);
float f[] = {2.3, 4.5, 6.6};
char[] c = new char();
3. Identify and fix the errors in the following code:
public class Test {
public static void main(String[] args) {
double[100] r;
for (int i = 0; i < r.length(); i++);
r(i) = Math.random * 100;
CPCS203 – The Lab Note
Lab-8
10
Term I
2011
Lab-8: Arrays
} }
4. Write a program that reads ten numbers, computes their average, and
finds out how many numbers are above the average.
5. Write a program that reads ten integers and displays them in the reverse of
the order in which they were read.
6. Write a program that reads an unspecified number of scores and
determines
how many scores are above or equal to the average and how many
scores are below the average. Enter a negative number to signify the
end of the input. Assume that the maximum number of scores is 100.
7. Write a method that finds the smallest element in an array of integers.
Use {1, 2, 4, 5, 10, 100, 2, –22} to test the method.
8. Write a method that sums all the integers 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.
9. 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.
10.Write a method that sums all the integers in the row 1 and column 2 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.
11.(Airline Reservations System)
A small airline has just purchased a computer for its new automated
reservations system. You have been asked to develop the new system. You are
to write an application to assign seats on each flight of the airline's only plane
(capacity: 10 seats).
Your application should display the following alternatives: Please type 1
for First Class and Please type 2 for Economy. If the user types 1, your
application should assign a seat in the first-class section (seats 15). If the
user types 2, your application should assign a seat in the economy
section (seats 610). Your application should then display a boarding pass
indicating the person's seat number and whether it is in the first-class or
economy section of the plane.
Use a one-dimensional array of primitive type boolean to represent the
seating chart of the plane. Initialize all the elements of the array to false
CPCS203 – The Lab Note
Lab-8
11
Term I
2011
Lab-8: Arrays
to indicate that all the seats are empty. As each seat is assigned, set the
corresponding elements of the array to true to indicate that the seat is
no longer available.
Your application should never assign a seat that has already been
assigned. When the economy section is full, your application should ask
the person if it is acceptable to be placed in the first-class section (and
vice versa). If yes, make the appropriate seat assignment. If no, display
the message "Next flight leaves in 3 hours."
4) Stage a2 (assess)
Lab Report:
The laboratory report of this lab (and also all the following labs in this manual)
should include the following items/sections:
A cover page with your name, course information, lab number and title,
and date of submission.
A summary of the addressed topic and objectives of the lab.
Implementation: a brief description of the process you followed in
conducting the implementation of the lab scenarios.
Results obtained throughout the lab implementation, the analysis of these
results, and a comparison of these results with your expectations.
Answers to the given exercises at the end of the lab. If an answer
incorporates new graphs, analysis of these graphs should be included here.
A conclusion that includes what you learned, difficulties you faced, and any
suggested extensions/improvements to the lab.
Note: only a softcopy is required for both homework and report, please do not
print or submit a hard copy.
CPCS203 – The Lab Note
Lab-8
12
© Copyright 2026 Paperzz