array t.

KING ABDULAZIZ UNIVERSITY
Faculty of Computing & Information Technology
Department of Computer Science
Lab Manual
CPCS204
Data Structures 1
1433/1434H
Lab - 2
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
2013
Lab-2: Array Concepts and Principles
Laboratory 2:
Statement Purpose:
This lab will give you an overview of Array Concepts and Principles.
Activity Outcomes:
This lab teaches you the following topics:




The basics of one-dimensional and 2-dimensional arrays.
Review of defining and handling array structure and elements.
Practicing the use of arrays in programming.
Employing arrays in some programming solutions.
Instructor Note:
As pre-lab activity, review Ch2, from the book Data Structures with Java by
John R. Hubbard and also the relevant instructor’s slides.
Names
I.D.
1. .……………..……………………………….
………………………………
2. ..……………………………………………..
………………………………
3. .……………………………………………...
………………………………
4. .……………………………………………..
..…………………………….
CPCS204 – The Lab Note
Lab-2
1
Term I
2013
Lab-2: Array Concepts and Principles
1) Stage J (Journey)
A. One-Dimensional Arrays:
Array Basics
 An array is used to store a collection of similar data type under one name.
 Instead of declaring individual variables, such as number0, number1, ...,
and number99, you declare one array variable such as numbers and use
numbers[0], numbers[1], and ..., numbers[99] to represent individual
variables.
 Declaring Array Variables
dataType[] arrayRefVar;
double[] myList;
Creating Arrays
 arrayRefVar = new dataType[arraySize]; OR
 dataType[]
arrayRefVar
=
new
dataType[arraySize];
for example,
double[] myList = new double[10];
CPCS204 – The Lab Note
Lab-2
2
Term I
2013
Lab-2: Array Concepts and Principles
B. Two-Dimensional Arrays:
Thus far, you have used one-dimensional arrays to model linear collections of
elements.
You can use a two-dimensional array to represent a matrix or a table.
Creating Two-Dimensional Arrays and Declaring its Variables
Here is the syntax for declaring a two-dimensional array:
dataType[][] arrayRefVar;
As an example, here is how you would declare a two-dimensional array
variable matrix of int values: int[][] matrix;
You can create a two-dimensional array of 5 by 5 int values and assign it to
matrix using this syntax: matrix = new int[5][5];
2) Stage a1 (apply)
Example 1:
CPCS204 – The Lab Note
Lab-2
3
Term I
2013
Lab-2: Array Concepts and Principles
import javax.swing.JOptionPane;
public class TestArray {
/** Main method */
public static void main(String[] args) {
final int TOTAL NUMBERS = 6;
int[] numbers = new int[TOTAL
NUMBERS
];
// 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);
}
}
Example 2: Assigning Grades
CPCS204 – The Lab Note
Lab-2
4
Term I
2013
Lab-2: Array Concepts and Principles
This example writes 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 > = - 10;
Grade is B if score is > = - 20;
Grade is C if score is > = - 30;
Grade is D if score is > = - 40;
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.
import javax.swing.JOptionPane;
public class AssignGrade {
/** Main method */
public static void main(String[] args) {
// Get number of students
String numberOfStudentsString =
JOptionPane.showInputDialog("Please enter number of
students:");
// Convert string into integer
int numberOfStudents =
Integer.parseInt(numberOfStudentsString);
int[] scores = new int[numberOfStudents];
// Array scores
int best = 0;
// The best score
char grade;
CPCS204 – The Lab Note
Lab-2
5
Term I
2013
Lab-2: Array Concepts and Principles
// The grade
// Read scores and find the best score
for (int i = 0; i < scores.length; i++) {
String scoreString =
JOptionPane.showInputDialog("Please enter a score:");
// Convert string into integer
scores[i] = Integer.parseInt(scoreString);
if (scores[i] > best) {
best = scores[i];
}
}
// Declare and initialize output string
String output = "";
// Assign and display grades
for (int i = 0; i < scores.length; i++) {
if (scores[i] >= best - 10) {
grade = 'A';
} else if (scores[i] >= best - 20) {
grade = 'B';
} else if (scores[i] >= best - 30) {
grade = 'C';
} else if (scores[i] >= best - 40) {
grade = 'D';
} else {
grade = 'F';
}
output += "Student " + i + " score is " +
scores[i] + " and grade is " + grade + "\n";
}
// Display the result
JOptionPane.showMessageDialog(null, output);
}
}
CPCS204 – The Lab Note
Lab-2
6
Term I
2013
Lab-2: Array Concepts and Principles
Example 3:
public class GradeExam {
/** Main method */
public static void main(String args[]) {
// Students' answers to the questions
char[][] answers = {
{'A', 'B', 'A', 'C', 'C', 'D', 'E', 'E',
'D'},
{'D', 'B', 'A', 'B', 'C', 'A', 'E', 'E',
'D'},
{'E', 'D', 'D', 'A', 'C', 'B', 'E', 'E',
'D'},
{'C', 'B', 'A', 'E', 'D', 'C', 'E', 'E',
'D'},
{'A', 'B', 'D', 'C', 'C', 'D', 'E', 'E',
'D'},
{'B', 'B', 'E', 'C', 'C', 'D', 'E', 'E',
'D'},
{'B', 'B', 'A', 'C', 'C', 'D', 'E', 'E',
'D'},
{'E', 'B', 'E', 'C', 'C', 'D', 'E', 'E',
'D'}};
// Key to the questions
char[] keys = {'D', 'B', 'D', 'C', 'C', 'D', 'A',
'A', 'D'};
// Grade all answers
for (int i = 0; i < answers.length; i++) {
// Grade one student
CPCS204 – The Lab Note
Lab-2
'A',
'A',
'A',
'A',
'A',
'A',
'A',
'A',
'E',
7
Term I
2013
Lab-2: Array Concepts and Principles
int correctCount = 0;
for (int j = 0; j < answers[i].length; j++) {
if (answers[i][j] == keys[j]) {
correctCount++;
}
}
System.out.println("Student " + i + "'s correct
count is " + correctCount);
}
}
}
Task 1:
NOW after compiling and running this example code in Netbeans IDE, try to
run the GradeExam.class and projectName.jar code file using CMD (i.e.
commend line program under windows OS) where the result should be as
follows:
3) Stage v (verify)
Programming Exercises
Ex-1: Find and correct the error in each of the following program segments:
1. final int ARRAY_SIZE = 5; ARRAY_SIZE = 10;
2. Assume int b[] = new int [ 10 ]; for ( int i = 0; i <=
b.length; i++ ) b[ i ] = 1;
3. Assume int a[][] = { { 1, 2 }, { 3, 4 } }; a[ 1, 1 ] = 5;
CPCS204 – The Lab Note
Lab-2
8
Term I
2013
Lab-2: Array Concepts and Principles
Ex-2: Consider a two-by-three (integer) array t.
1. Write a statement that declares and creates t.
2. How many rows does t have?
3. How many columns does t have?
4. How many elements does t have?
5. Write the names of all the elements in the second row of t.
6. Write the names of all the elements in the third column of t.
7. Write a single statement that sets the element of t in row 1 and column 2
to value of 5.
8. Write a nested for statement that initializes each element of t to value of 1.
9. Write a nested for statement that inputs the values for the elements of t
from the user.
10.Write a statement that displays the elements of the first row of t.
11.Write a statement that totals the elements of the third column of t.
12.Define a method called printArray(int [][] arr)that receive
two-by-three integer array and print its elements such that:
If arr={{1,2,3},{4,5,6}};
The output of printing
------------------1 2 3
4 5 6
------------------13.Use printArray()Use method to print t array after the steps (1, 7, 8, and
9).
CPCS204 – The Lab Note
Lab-2
9
Term I
2013
Lab-2: Array Concepts and Principles
Ex-3:
1. Write a program that reads ten numbers, computes their average, and
finds out how many numbers are above the average.
2. Write a program that reads ten integers and displays them in the reverse of
the order in which they were read.
3. Write a program that reads ten numbers and prints the Maximum and
Minimum number among the entered ten numbers.
4. Write a program 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.
4) Stage a2 (assess)
Lab Work:
In each laboratory you are assessed on your work within lab session based on
your participation, discussions and achievement of lab activities. Thus, each lab
has a portion of the (LAB WORK MARK). Therefore, a checklist of each lab is
used to evaluate your work. This checklist accounts the following criteria:






Following the lab manual step by step
Answering given questions concisely and precisely
Practicing and implementing given examples correctly
Writing code of required programming tasks
Being focused, positive, interactive and serious during lab session
Asking good questions or answering instructor questions if any
Note: performing given home activities or extra programming is highly
recommended to improve your understanding, capability and programming
skills.
CPCS204 – The Lab Note
Lab-2
10