Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

W1 Chapter Revision Array

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 74

STIA2024

Data Structures & Algorithm


Analysis

Week 3
Arrays Revision

1
Lecture Outline
• Review the Arrays
• Define and create Arrays of Objects
• Two-Dimensional Arrays

2
Learning Objectives
• To define and use arrays for basic data
organization.
• To discuss the issues related to arrays as objects
and array of objects.
• To create and use multidimensional arrays.
Array
• Consider the following program (input underlined):
How many days' temperatures? 7
Day 1's high temp: 45
Day 2's high temp: 44
Day 3's high temp: 39
Day 4's high temp: 48
Day 5's high temp: 37
Day 6's high temp: 46
Day 7's high temp: 53
Average temp = 44.57142857142857
4 days were above average.
• We need the temperatures to compute the average, and again to tell how
many were above average.

4
Array
• An array is a collection of data values.
• If your program needs to deal with 100 integers, 500
Account objects, 365 real numbers, etc., you will use
an array.
• In Java, an array is an indexed collection of data
values of the same type.
• Types of Arrays:
- one-dimensional array
- two-dimensional array
- multidimensional array
Arrays
• array: A variable that stores many values of the same type.
– element: One value in an array.
– index: A 0-based integer used to access an element from
an array.
• We usually draw an array as a row or column of boxes.
– Example: an array of ten integers

index 0 1 2 3 4 5 6 7 8 9
value 12 49 -2 26 5 17 -6 84 72 3

element 0 element 4 element 9


6
Arrays of Primitive Data Types
• Array Declaration
<data type> [ ] <variable> //variation 1
<data type> <variable>[ ] //variation 2
• Array Creation
<variable> = new <data type> [ <size> ]

• Example
Variation 1 Variation 2
int[ ] numbers; int numbers[ ];
numbers = new int[7]; numbers = new int[7];
Array auto-initialization
• When arrays are initially constructed, every element is automatically initialized
to a "zero-equivalent" value.
– int: 0
– double: 0.0
– boolean: false
– char: '\0' (the "null character")
– String or object: null (null means "no object")

An array of integers
inde 0 1 2 3 4
x
value 0 0 0 0 0

inde
An array of real numbers 0 1 2 3
x
value 0.0 0.0 0.0 0.0 8
Accessing array elements
• Assigning a value to an array element:
<array name> [ <index> ] = <value> ;

– Example:
numbers[0] = 27;
numbers[3] = -6;
index 0 1 2 3 4 5 6 7 8 9

value 27 0 0 -6 0 0 0 0 0 0

9
Accessing array elements
• Using an array element's value in an expression:
<array name> [ <index> ]

– Example:
System.out.println(numbers[0]);
if (numbers[3] < 0) {
System.out.println("Element 3 is
negative.");
} numbers[3]
index 0 1 2 3 4 5 6 7 8 9

value 27 0 0 -6 0 0 0 0 0 0
10
Out-of-bounds indexes
• The indexes that are legal to access in an array are those in the range of 0
to the array's length - 1.
– Reading or writing any index outside this range will throw an
ArrayIndexOutOfBoundsException.

• Example:
int[] data = new int[10];
System.out.println(data[0]); // okay
System.out.println(data[-1]); // exception
System.out.println(data[9]); // okay
System.out.println(data[10]); // exception

index 0 1 2 3 4 5 6 7 8 9

value 0 0 0 0 0 0 0 0 0 0
11
Arrays of other types
• Arrays can contain other types, such as double.
– Example:
double[] results = new double[6];
results[2] = 3.4;
results[5] = -0.5;
inde 0 1 2 3 4 5
x
value 0.0 0.0 3.4 0.0 0.0 -0.5

– Example:
boolean[] tests = new boolean[6];
tests[3] = true;
inde 0 1 2 3 4 5
x 12
Arrays and for loops
• Arrays are very commonly used with for loops that pass over
each element and process it in some way:

– Example (print each element of an array):


for (int i = 0; i < 8; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println(); // end the line of output

– Output (when used on array from previous slide):


0 4 11 0 44 0 0 2

13
More arrays and for loops
• Sometimes we assign each array element a value in a for loop.
– Example:
for (int i = 0; i < 8; i++) {
numbers[i] = 2 * i;
} index 0 1 2 3 4 5 6 7 numbers
value 0 2 4 6 8 10 12 14

• What values would be stored into the array after this code?
for (int i = 0; i < 8; i++) {
numbers[i] = i * i;
}
value 0 1 4 9 16 25 36 49
14
The .length field
• An array's length field stores its number of elements.
– General syntax:
<array name> .length

– It does not use parentheses like a String's .length() .

• Example (using array from previous slide):


for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
– Output:
0 1 4 9 16 25 36 49
• What expression refers to the last element of the array? The middle
element?

15
Why are arrays useful?
• Arrays store a large amount of data in one variable.
– Example: Read in a file of 1000 numbers, then print out the numbers in
reverse order.

• Arrays help us group related data into elements.


– Example: For a school exam, open a file of exam scores and count how
many students got each score from 0 through 100.

• Arrays let us access data in random order.


– Example: Read a file of weather data, store each month's weather stats
as an element in a large array, and then examine the stats to find
overall weather statistics for the year.

16
Array initialization statement
• Quick array initialization, general syntax:
<type> [] <name> = {<value>, <value>, ..., <value>};

– Example:
int[] numbers = {12, 49, -2, 26, 5, 17, -6};

index 0 1 2 3 4 5 6

value 12 49 -2 26 5 17 -6

– This syntax is useful when you know in advance what the array's element values will be.
– You don't explicitly specify the array's size in this syntax.
• The Java compiler figures out the size by looking at the number of values written between { and }.

17
Array Initialization
• Like other data types, it is possible to declare and
initialize an array at the same time.
int[] number = { 2, 4, 6, 8 };

double[] samplingData = { 2.443, 8.99, 12.3, 45.009, 18.2,


9.00, 3.123, 22.084, 18.08 };

String[] monthName = { "January", "February", "March",


"April", "May", "June", "July",
"August", "September", "October",
"November", "December" };

number.length 4
samplingData.length 9
monthName.length 12
Variable-size Declaration
• In Java, we are not limited to fixed-size array
declaration.
• The following code prompts the user for the size of an
array and declares an array of designated size:
int size;

int[] number;

System.out.print(“Size of an array = “)
size= Integer.parseInt(input.readLine());
number = new int[size];
Array practice problem
• What element values are stored in the following array?

int[] a = {2, 5, 1, 6, 14, 7, 9};


for (int i = 1; i < a.length; i++) {
a[i] += a[i - 1];
}

index 0 1 2 3 4 5 6

value 2 7 8 14 28 35 44

20
The Arrays class
• The Arrays class in package java.util has several useful static
methods for manipulating arrays:

Method name Description


binarySearch(array, value) returns the index of the given value in
this array (< 0 if not found)
equals(array1, array2) returns true if the two given arrays
contain exactly the same elements in the
same order
fill(array, value) sets every element in the array to have
the given value
sort(array) arranges the elements in the array into
ascending order
toString(array) returns a string representing the array,
such as "[10, 30, 17]"
21
Arrays.toString
• The Arrays.toString method is useful when you want to print an
array's elements.
– Arrays.toString accepts an array as a parameter and returns the String
representation, which you can then print.

– Example:
int[] a = {2, 5, 1, 6, 14, 7, 9};
for (int i = 1; i < a.length; i++) {
a[i] += a[i - 1];
}
System.out.println("a is " + Arrays.toString(a));

Output:
a is [2, 7, 8, 14, 28, 35, 44]

22
Weather problem

• Use an array to solve the following problem:


How many days' temperatures? 7
Day 1's high temp: 45
Day 2's high temp: 44
Day 3's high temp: 39
Day 4's high temp: 48
Day 5's high temp: 37
Day 6's high temp: 46
Day 7's high temp: 53
Average temp = 44.57142857142857
4 days were above average.

23
Weather solution
// This program reads several days' temperatures from the user
// and computes the average and how many days were above average.
import java.util.*;
public class Weather {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many days' temperatures? ");
int days = console.nextInt();
int[] temperatures = new int[days]; // array to store days' temperatures
int sum = 0;
for (int i = 0; i < days; i++) { // read/store each day's temperature
System.out.print("Day " + (i + 1) + "'s high temp: ");
temperatures[i] = console.nextInt();
sum += temperatures[i];
}
double average = (double) sum / days;
int count = 0; // see if each day is above average
for (int i = 0; i < days; i++) {
if (temperatures[i] > average) {
count++;
}
}
// report results
System.out.println("Average temp = " + average);
System.out.println(count + " days above average");
}
}

24
Rainfall Solution
• Create an array to store rainfall data in a month.
double[] rainfall = new double[12];

rainfall
0 1 2 3 4 5 6 7 8 9 10 11

The index of the first This


Thisindexed
refers
indexedexpression
expression
refers to the elementatat
to the element
position in an array is 0. rainfall[2] position
position#2#2
Rainfall Solution
Scanner console = new Scanner(System.in);
double[] rainfall = new double[12];
double annualAverage,
sum = 0.0;

for (int i = 0; i < rainfall.length; i++) {

System.out.print(“Rainfall for month “+(i+1)+” =“);


rainfall[i] = console.nextDouble();
sum += rainfall[i];
}
annualAverage = sum / rainfall.length;
System.out.println("Average is = "+anualAverage);
Rainfall Solution – Output
Rainfall for month 1=100.00
Rainfall for month 2=120.00
Rainfall for month 3=200.00
Rainfall for month 4=200.00
Rainfall for month 5=300.00
Rainfall for month 6=150.00
Rainfall for month 7=100.00
Rainfall for month 8=145.00
Rainfall for month 9=125.00
Rainfall for month 10=200.00
Rainfall for month 11=200.00
Rainfall for month 12=300.00
Average is = 178.33
Press any key to continue...
Array Operation: traversal
• traversal: An examination of each element of an array.

– Traversal algorithms often take the following form:


for (int i = 0; i < <array>.length; i++) {
do something with <array> [i];
}
• Traversals are useful in many situations:
– printing the elements of an array
– searching an array for a specific value
– rearranging the elements of an array
– computing the sum, product, etc. of an array's elements
– ...

28
Array Operation: Printing array elements
• Example (print each element of an array on a line):
int[] list = {4, 1, 9, 7};
for (int i = 0; i < list.length; i++) {
System.out.println(i + ": " + list[i]);
}
Output:
0: 4
1: 1
2: 9
3: 7
• How could we change the code to print the following?
4, 1, 9, 7
(Do not use Arrays.toString.)

29
Array Operation: Examining array elements
• Example (find the largest even integer in an array):
int[] list = {4, 1, 2, 7, 6, 3, 2, 4, 0, 9};
int largestEven = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] % 2 == 0 && list[i] > largestEven) {
largestEven = list[i];
}
}
System.out.println("Largest even: " + largestEven);

Output:
Largest even: 6

30
Using Array Element as Parameters
double n = 0.0;
double[] a = {2.3, 4.5, 6.7, 8.9};
int i = 2;

Given the method declaration


public void myMethod (double x)
{
:
}

then all of the following are legal:


myMethod(n); //n evaluates to 0.0
myMethod(a[3]); //a[3] evaluates to 8.9
myMethod(a[i]); //i evaluates to 2,
//a[2] evaluates to 6.7

31
Arrays as parameters
• Arrays are objects.
– When they are passed as parameters, they are passed by reference.
– Changes made in the method will also be seen by the caller.

– Example:
public static void main(String[] args) {
int[] iq = {126, 167, 95};
System.out.println(Arrays.toString(iq));
doubleAll(iq);
System.out.println(Arrays.toString(iq));
}
public static void doubleAll(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = 2 * array[i];
}
}
– Output:
[126, 167, 95]
[252, 334, 190]

32
Arrays as parameters
• An array can be passed as a parameter.

– Syntax (declaration):
public static <type> <name>(<type>[] <name>) {

– Example:
public static double average(int[] numbers) {

– Syntax (call):
<method name>(<array name>);
– Example:
int[] scores = {13, 17, 12, 15, 11};
double avg = average(scores);

33
Array parameter: example
• Array as parameter example:
public static void main(String[] args) {
int[] iq = {126, 167, 95};
int result = max(iq);
System.out.println("Max = " + result);
}
public static int max(int[] array) {
int largest = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > largest) {
largest = array[i];
}
}
return largest;
}
• Output:
Max = 167

34
Array parameter diagram
iq
public static void main(String[] args) {
int[] iq = 126, 167, 95};
System.out.println(Arrays.toString(iq));
doubleAll(iq);
System.out.println(Arrays.toString(iq));
}
array
public static void doubleAll(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = 2 * array[i];
}
}
– Output:
[126, 167, 95]
[252, 334, 190]

index 0 1 2

value 126
252 167
334 190
95
35
Arrays as return values
• An array can also be returned from a method.

– Syntax (declaration):
public static <type>[] <name>(<parameters>) {

– Example:
public static int[] readAllNumbers(Scanner input) {

– Syntax (call):
<type>[] <name> = <method name>(<parameters>);
– Example:
Scanner fileScan = new Scanner(new
File("weather.dat"));
int[] numbers = readAllNumbers(fileScan);
36
Array return example
public static void main(String[] args) {
int a = 100;
int[] numbers = initArray(a);
System.out.println(Arrays.toString(numbers));
}

public static int[] initArray(int n) {


int[] temp = new int[10];
for (int i = 0; i <= 9; i++)
temp[i] = n;
}
return temp;
}
Output:
100,100,100,100,100,100,100,100,100,100]

37
Array parameter: Exercise
• Write a method named average that accepts an array of
integers as its parameter and returns the average of the
values in the array.
• Write a method named contains that accepts an array of
integers and a target integer value as its parameters and
returns whether the array contains the target value as one of
its elements.
• Write a method named roundAll that accepts an array of
doubles as its parameter and modifies each element of the
array so that it is rounded to the nearest whole number.

38
Array parameter: Solutions
public static double average(int[] numbers) {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return (double) sum / numbers.length;
}
public static boolean contains(int[] values, int target) {
for (int i = 0; i < values.length; i++) {
if (values[i] == target) {
return true;
}
}
return false;
}
public static void roundAll(double[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = Math.round(array[i]);
}
}

39
Arrays of Objects

• In Java, in addition to create arrays of


primitive data types (int, double,
float, char etc), we can declare arrays
of objects
• An array of primitive data is a powerful tool,
but an array of objects is even more powerful.
• The use of an array of objects allows us to
model the application more cleanly and
logically.
Declaring an Object Array
Code AA Person[ ] person;
Only
Onlythe
thename
nameperson
personisis
person = new Person[20];
declared,
declared,no
noarray
arrayisis
person[0] = new Person( ); allocated
allocatedyet.
yet.

person

State
of
Memory
After AA is executed
Creating an Object Array
Code Person[ ] person; Now
Nowthe
thearray
arrayfor
forstoring
storing20
20
Person objects is created,
Person objects is created,
BB person = new Person[20]; but
butthe
thePerson
Personobjects
objects
themselves
themselves are notyet
are not yet
person[0] = new Person( );
created.
created.

person

0 1 2 3 4 16 17 18 19

State
of
Memory
After BB is executed
Creating an Object Array
Code Person[ ] person;
One
OnePerson
Personobject
objectisiscreated
created
person = new Person[20]; and the reference to this
and the reference to this
object
objectisisplaced
placedininposition
position0.0.
CC person[0] = new Person( );

person

0 1 2 3 4 16 17 18 19

State
of Person

Memory
After CC is executed
Creating an Object Array
Code for(int i=0;i<Person.length;i++) 2020Person
Personobjects
objectsareare
D
D person[i] = new Person( );
created
to
and the reference
created and the reference
tothese
theseobjects
objectsare
areplaced
placed
ininposition 0 to 19.
position 0 to 19.

person After D
D is executed
0 1 2 3 4 16 17 18 19

State
of
Person

Person

Person

Person
Person

Person

Person

Person

Person
Memory
Array of Object - Sample
public class Rectangle
{
private int length,width,area;

public Rectangle (int l, int w){


length = l;
width = w;
}

public void calculateArea() {


area = length * width;
}

public int getArea() {


return area;
}

} // end class
Array of Object- Sample
import java.util.*;
public class TestRectangle{
public static void main (String []args)
{
static Scanner console = new Scanner(System.in);
Rectangle rect[]=new Rectangle[2];
for (int j=0;j<rect.length;j++){
System.out.print("Length : ");
int length = console.nextInt();
System.out.print("Width: ");
int width = console.nextInt();
rect[j]=new Rectangle(length,width);
rect[j].calculateArea();
System.out.println("Area of Rectangle " + (j+1) + " = " +
rect[j].getArea());
System.out.println();
}
}
}//end class
Array of Object- Sample
import java.io.*;

class Person
{
private String name;
private int age;
private char gender;

public Person(String newName, int newAge, char newGender){


name = newName;
age = newAge;
gender = newGender;
}
Array of Object- Sample

public String getName(){


return name;
}

public int getAge()


{
return age;
}

public char getGender()


{
return gender;
}
}
Array of Object- Sample
class PersonList{
private Person [] person;
private int counter;

public PersonList(int size){


person = new Person[size];
counter = 0;
}
public void addRecord(String name, int age, char gender) {
person[counter] = new Person(name,age,gender);
counter++;
}

public void displayRecord(){


for (int i= 0; i< counter; i++){
System.out.println("\nName ="+person[i].getName());
System.out.println("Age = "+person[i].getAge());
System.out.println("Gender = "+person[i].getGender());
}
}

} // end PersonList
Array of Object- Sample
import java.util.*;
public class TestPerson {
public static void main(String[] arg){
Scanner read = new Scanner(System.in);
String name=null;
int age;
char gender;
System.out.println("Enter number of person: ");
int num = read.nextInt();
PersonList people = new PersonList(num);
System.out.println("\n");
for (int i= 0; i< num; i++) {
System.out.print("\nEnter name = ");
name = read.next();
System.out.print("Enter age = ");
age = read.nextInt();
System.out.print("Enter gender = ");
gender = read.nextLine().charAt(0);
people.addRecord(name,age,gender);
}
people.displayRecord();
}
} // end TestPerson
Array of Object- Sample
Output:
Enter number of person: 2

Enter name = MuthuSamy a/l Acaphan


Enter age = 23
Enter gender = male

Enter name = Siti Sarah binti Zakaria


Enter age = 19
Enter gender = female

Name = MuthuSamy a/l Acaphan


Age = 23
Gender =m

Name = Siti Sarah binti Zakaria


Age = 19
Gender =f
Process Exit...
Array of Object- Sample
• Find the youngest and oldest persons.
int minIdx = 0; //index to the youngest person
int maxIdx = 0; //index to the oldest person

for (int i = 1; i < person.length; i++) {

if ( person[i].getAge() < person[minIdx].getAge() ) {


minIdx = i; //found a younger person

} else if (person[i].getAge() > person[maxIdx].getAge() ) {

maxIdx = i; //found an older person


}
}

//person[minIdx] is the youngest and person[maxIdx] is the oldest


Array of Object- Sample
Object Deletion – Approach 1

Delete
DeletePerson
PersonBBbybysetting
setting
AA int delIdx = 1; the
the reference in position11toto
reference in position
person[delIdx] = null; null.
null.

person person

0 1 2 3 0 1 2 3

AA BB CC DD AA CC DD

Before AA is executed After AA is executed


Array of Object- Sample
Object Deletion – Approach 2

AA int delIdx = 1, last = 3; Delete


DeletePerson
PersonBBbybysetting
setting
person[delIndex] = person[last]; the
the reference in position11toto
reference in position
the
thelast
lastperson.
person.
person[last] = null;

person person

0 1 2 3 0 1 2 3

AA BB CC DD AA DD CC

Before AA is executed After AA is executed


Array of Object- Sample
• Searching for a particular person. Approach 2 Deletion is used.

int i = 0;

while ( person[i] != null && !person[i].getName().equals("Latte") ) {


i++;
}

if ( person[i] == null ) {
//not found - unsuccessful search
System.out.println("Ms. Latte was not in the array");

} else {
//found - successful search
System.out.println("Found Ms. Latte at position " + i);
}
Array of Object- Sample
Object Deletion – Approach 1

Delete
DeletePerson
PersonBBbybysetting
AA int delIdx = 1; the
setting
the reference in position11toto
reference in position
person[delIdx] = null; null.
null.

person person

0 1 2 3 0 1 2 3

AA BB CC DD AA CC DD

Before AA is executed After AA is executed


Array of Object- Sample
Object Deletion – Approach 2

AA int delIdx = 1, last = 3; Delete


DeletePerson
PersonBBbybysetting
setting
person[delIndex] = person[last]; the
the reference in position11toto
reference in position
the
thelast
lastperson.
person.
person[last] = null;

person person

0 1 2 3 0 1 2 3

AA BB CC DD AA DD CC

Before AA is executed After AA is executed


Two-dimensional Arrays
• Two-dimensional arrays are useful in representing tabular information.
Two-dimensional Arrays
Declaration a two-dimensional arrays
<data type> [][] <variable> //variation 1
<data type> <variable>[][] //variation 2
Creation a two-dimensional arrays
<variable> = new <data type> [intRow][intColumn ]
Example

payScaleTable
0 1 2 3 4
double[][] payScaleTable; 0
payScaleTable 1
= new double[4][5];
2
3
Two-dimensional Arrays
• An element in a two-dimensional array is accessed by
its row and column index.
Two-dimensional Arrays
• Find the average of each row.

double[ ] average = { 0.0, 0.0, 0.0, 0.0 };

for (int i = 0; i < payScaleTable.length; i++) {

for (int j = 0; j < payScaleTable[i].length; j++) {

average[i] += payScaleTable[i][j];
}

average[i] = average[i] / payScaleTable[i].length;


}
Two-dimensional Arrays
• E.g.
• Initialization
• Print
• Input data/store data into 2-Dimensional array
• Sum the data
• Find the largest element
• Suppose the declaration as below:

int row;

int column;

int matix = new int[7][6];


Two-dimensional Arrays
Initialization
for (row = 0; row < matrix.length; row++)
for (col = 0; col < matrix[row].length; col++)
matrix[row][col] = 10;

matrix
Two-dimensional Arrays
Print

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


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

Read Data

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


for (col = 0; col < matrix[row].length; col++)
matrix[row][col] = console.nextInt();
Two-dimensional Arrays
Sum by Row

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


{
sum = 0;
for (col = 0; col < matrix[row].length; col++)
sum = sum + matrix[row][col];
System.out.println(“Sum of row” + (row + 1) + “ = “+ sum);
}

Sum by Column

for (col = 0; col < matrix[0].length; col++)


{
sum = 0;
for (row = 0; row < matrix.length; row++)
sum = sum + matrix[row][col];
System.out.println(“Sum of column” + (col + 1) + “=“+ sum);
}
Two-dimensional Arrays
Largest Element in Each Row

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


{
largest = matrix[row][0];
for (col = 1; col < matrix[row].length; col++)
if (largest < matrix[row][col])
largest = matrix[row][col];
System.out.println(“The largest element of row” + (row+1)
+ “=“ + largest);
}
Multi-dimensional Arrays
• Can define three-dimensional arrays or n-dimensional arrays
(n can be any number).
• Syntax to declare and instantiate array:
dataType[][]…[] arrayName = new
dataType[intExp1][intExp2]…[intExpn];

• Syntax to access component:


arrayName[indexExp1][indexExp2]…[indexExpn]
• intExp1, intExp2, ..., intExpn = positive integers
• indexExp1,indexExp2, ..., indexExpn = non-negative
integers
Multi-dimensional Arrays
double[][][] carDealers = new double[10][5][7];

for (i = 0; i < 10; i++)


for (j = 0; j < 5; j++)
for (k = 0; k < 7; k++)
carDealers[i][j][k] = 10.00;
Exercise1: Grade
• Write a Java program that reads students’ details (including name, matric
number and score) for 10 number of students. Then finds grades for the
specified scores based on following scheme:
• Grade A if score between 80 – 100
• Grade B if score between 65 – 79
• Grade C if score between 50 – 64
• Grade D if score between 40 – 49
• Grade F if score between 0 – 39
The output produced should follow the following format:
Name Matric No. Score Grade
Ali s1111 85 A
Siti s3333 45 D
………………………………………..
Please create appropriate classes to accomplish the above task.
Excercise2: Shifting Element
• Imagine we want to 'rotate' the elements of an array; that is, to shift
them left by one index.
– The element that used to be at index 0 will move to the last slot in the array.
– For example, {3, 8, 9, 7, 5} becomes {8, 9, 7, 5, 3}.
Before: index 0 1 2 3 4

value 3 8 9 7 5

index 0 1 2 3 4
After: value 8 9 7 5 3

– Shifting elements is useful when inserting and removing values from arrays
after they have already been filled with data.

70
Excercise2: Shifting Element
• A left shift of the elements of an array:

index 0 1 2 3 4

value 3 8 9 7 5

index 0 1 2 3 4

value 8 9 7 5 3

• Let's write the code to do the left shift.


– Can we generalize it so that it will work on an array of any size?
– Can we write a right-shift as well?

71
Exercise: The 2-Dimensional Array grade
Write a Java program that meet the requirements as in Display 6.19:

72
References
 Thomas Wu. C, An Introduction To Object-Oriented
Programming With Java. (2006). Mc Graw Hill.
 Liang, D. (2006). Introduction To Java programming. Prentice
Hall.
 Malik, D. S. (2006). Java Programming: from Problem Analysis
to Program Design, Thomson Course Tech.
Conclusion

Q & A Session

74

You might also like