0% found this document useful (0 votes)
0 views25 pages

CSI247-04 Array

The lecture covers the fundamentals of one-dimensional arrays in Java, including declaration, initialization, and manipulation of arrays. It discusses common operations such as adding and retrieving elements, as well as using arrays as parameters in methods. Additionally, it addresses potential errors like Array Index Out of Bounds and provides examples of processing arrays of objects.

Uploaded by

plutoagcorp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views25 pages

CSI247-04 Array

The lecture covers the fundamentals of one-dimensional arrays in Java, including declaration, initialization, and manipulation of arrays. It discusses common operations such as adding and retrieving elements, as well as using arrays as parameters in methods. Additionally, it addresses potential errors like Array Index Out of Bounds and provides examples of processing arrays of objects.

Uploaded by

plutoagcorp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

CSI247: Data Structures

Lec04: Review (Arrays)


B. Gopolang & T. Taukobong
(Semester 1, 2023/24)

1
LECTURE OBJECTIVES

By the end of this lecture you must be able to:


• Declare and initialize a one dimensional array
• Add elements into the array
• Retrieve elements from the array
• Use arrays as formal parameters to methods
• Process Arrays of Objects, e.g. Array of Dogs

2
Collection
Collection:
A group or set of related things(objects). Any two
objects in a collection should be comparable.

Examples
A collection of music CDs.
A collection of books.
A collection of QBoards, Strings, Accounts, etc.

We want to be able to write Java programs that create and


manipulate collections.

3
Problem

Write a Java application that reads 10 lab marks from


the keyboard. The application should then output all
marks that are greater or equal to the average mark.

4
Possible solution?
import java.util.∗;
public class ComputeAverage {
public static void main (String[ ] args) {
Scanner scan = new Scanner (System.in);
double mark, average, sum = 0.0;
for (int i = 1 ; i <= 1 0 ; i++){
System.out.printf("Enter lab mark");
mark = scan.nextDouble();
sum += mark;
}
average = sum/10;
// then what ?
}
5
What is wrong with the approach?

We lost all the marks


except the last one before
determining those greater
or equal to average.

6
Solution?
Arrays

Array:
An object that allows us to store items of the
same kind (collection).
Each item/object is stored in its own cell.
Cells are numbered from 0 to array.length − 1.
It supports the following operations:
• add an item/element
• retrieve an item/element

7
1. Creating One Dimensional Arrays

Syntax: (one line)


dataType[] identifier = new dataType[intExp];

Syntax: (two lines)


dataType[] identifier;
identifier = new dataType[intExp];

• intExp is an expression that evaluates to an integral


value (byte, short, int, long)

Question: Can we use a double expression?

8
2. Creating Arrays: Memory Model
int[ ] numbers = new int[10]; // array to hold 10 integers
numbers
48
48

0 1 2 3 4 5 6 7 8 9

String[ ] courses = new String[7]; // array to hold 7 references


courses
to String objects
99
99

0 1 2 3 4 5 6
9
3. Creating and Initializing Arrays
Declare and Initialize:
int[] nums = {10, 6, -7, 9, 19};
char[] grades = {’A’, ’B’, ’C’, ’D’, ‘E’, ‘F’};
String[] villages = {”Mochudi”, ”Serowe”, ”Kanye”}

Declare, Create , Assign:


int[] data; // declare an array of int values
data = new int[5]; // create array with space for 5 int values
data[0] = 10; data[1] = 6; data[2] = -7; … // store values into
the array

10
4. Adding Values to an Array
An array object has the attribute length, which is public.
• Its value is the number of cells in the array.
◦ WARNING!!! This is not a method!!!
Syntax (for adding a value):
arrayName[intExp] = expression;
• intExp is an integral expression, called the index, satisfying
0 <= intExp <= arrayName.length − 1.
Notice that arrayName[intExp] is used as a variable!
int n =10;
int[] numbers = new int[n+4];
for (int i = 0; i < numbers.length; i++){
if ( i%2 ==1)
numbers[i] = i+1;
} 11
The Big Picture
numbers
50
50
2 4 6 8 10 12 14
0 1 2 3 4 5 6 7 8 9 10 11 12 13

What is the output of the following Java statement?


System.out.printf(“%d\n”,numbers.length);

12
5. Array Index Out of Bounds
Array IndexOutOfBounds:
An error you get if you try to access a non-existent
cell of the array.
Can only be caught at run-time.

Example
int[] numbers = new int[10];

In the above example, array indices go from 0 to


numbers.length - 1, which is 9.
numbers[-1] or numbers[10] or numbers[12] causes a
run-time error.
13
6. Retrieving Values From An Array
General form used: arrayName[intExp]
• where intExp is called the index.
arrayName[intExp] can be used in two ways:
• as the memory location with index intExp (left of =)and
• as the value stored at the memory location with index intExp (right of
=).
What are the contents of array numbers after executing the following
code?
int[] numbers= new int[6];
numbers[0] = 5 ;
for (int i = 1 ; i<numbers.length; i++){
numbers[i] = i ∗i+5;
if (i > 2) {
numbers [i] = 2∗numbers [i] − numbers [i−1];
}
}
14
7. Declaring Arrays as Formal Parameters
We do this to pass an array to a method.
Remember Syntax:
dataType[] identifier;

Example
public class PassArrays {
// method returns true if x is in the array listA
public boolean search (int[] listA, int x) {
boolean found = false;
for (int i= 0; i<listA.length; i++){
if (listA[i] == x )
found = true;
}
return found;
}
} 15
To use the method:

int[] numbers = {3,1,-2,6,8};


int num = 16;
PassArrays pa = new PassArrays();
System.out.printf(“%s\n”, pa.search(numbers, num));

16
a) Initializing an Array to a Specific Value
public void initArray (int[] numbers, int initValue) {
for (int i = 0; i < numbers.length; i++){
numbers[i] = initValue;
}
}
Method invoked by giving it an (integer) array and an
integer value to initialize the array cells with.
• The array numbers MUST have been created,
otherwise NullPointerException will be raised.

17
b) Reading Data into an Array
public void readIntoArray(int[ ] numbers, Scanner sc)
for (int i = 0; i < numbers.length; i++){
numbers[i] = sc.nextInt();
}
}
Method invoked by giving/passing it an (integer)
array AND a Scanner object.
• Both the array and the Scanner object MUST have
been created.

18
c) Printing an Array
public void printArray (int[ ] numbers) {
System.out.printf(“{"); // for formatting output
for (int i = 0; i < numbers.length; i++){
System.out.printf(“%d ”, numbers[i])
}
System.out.printf(“}");
}
Method invoked by giving it an (integer) array.
• The array MUST have been created.

19
d) Determining Index of the Largest Element
public int indexOfMax(int[ ] numbers) {
int index = 0; //Assume numbers[0] has max
for (int i = 0; i < numbers.length; i++){
if (numbers[i] > numbers[index])
index = i;
}
return index;
}
Method invoked by giving it an (integer) array.
• The array MUST have been created.
It returns an integer indicating the position of the largest
element in the array.
20
e) Determining the Average
public double computeArrayAverage( int[ ] numbers) {
double sum = 0.0;
double average = 0.0;
for (int i=0; i < numbers.length; i++){
sum = sum + numbers[i];
}
if (numbers.length != 0)
average = sum/numbers.length;
return average;
}
Method invoked by giving it an (integer) array.
• The array MUST have been created.
It returns average of elements in the array. 21
8. Arrays of String Objects
Declaring:
String[] classList = new String[5];

To add names to the array:


classList[0] = ”Ame” ;
// same as: classList[0] = new String(”Ame”);

classList[i] is treated like any String variable:


System.out.printf(“%d\n”, classList[0].length());
System.out.printf(“%s\n”,classList[0].toUpperCase());
System.out.printf(“%s\n”,classList[0].charAt(2));
System.out.printf(“%d\n”,classList[0].indexOf(’e’));
System.out.printf(“%d\n”,classList[0].indexOf(’f’));
System.out.printf(“%s\n”,classList[0].equals(”ame”));
22
9. Arrays of Objects of Other Classes
Declaring:
ClassName[] identifier = new ClassName[intExp];

Example:
Dog[] dogs = new Dog[5];

To add Qboards to the array:


dogs[0] = new Dog(“Fluffy”, 1);

System.out.printf(“%d\n”, dogs[0].getName());
System.out.printf(“%s\n”,dogs[0]. computeDogYears());
23
Another Example:

Account[] accs= new Account[8];

To add Accounts to the array:


accs[4] = new Account();

accs[i] is treated like any Account variable:


• accs[0].setBalance(500.55));
• System.out.printf(“%d\n”, accs[0].getBalance());
• System.out.printf(“%s\n”, accs[0].equals(accs[3]);

24
Summary
1. Collections
2. One Dimensional Arrays
3. Array Index Out of Bounds Error
4. Declaring Arrays as Formal Parameters
5. Processing One Dimensional Arrays with Methods
6. Arrays of Objects

25

You might also like