0% found this document useful (0 votes)
36 views31 pages

Lec14 - Object Oriented programmingIIIaudio

The document discusses arrays in object oriented programming. It defines an array as an ordered collection of data items that can be primitive types or object references. It describes how to declare, initialize, access, and manipulate array elements using indexes. Examples show calculating averages from arrays and finding the maximum value and its index in an array. The document also introduces parallel arrays and recommends using arrays of user-defined objects to associate multiple data values instead.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views31 pages

Lec14 - Object Oriented programmingIIIaudio

The document discusses arrays in object oriented programming. It defines an array as an ordered collection of data items that can be primitive types or object references. It describes how to declare, initialize, access, and manipulate array elements using indexes. Examples show calculating averages from arrays and finding the maximum value and its index in an array. The document also introduces parallel arrays and recommends using arrays of user-defined objects to associate multiple data values instead.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 31

Object Oriented ProgrammingIII

Agatha Amara Turyagyenda


Lecture Fourteen
Arrays

What if you have a large collection of identical data items which you want to
process.
Examples :
• Sort n numbers.
• Compute the diameter of a set of 100 points in 2-D space.
• Compute the smallest enclosing sphere for a set of 10000 points in 3-D
space.
We need an easy way to identify and manipulate large number of variables
Arrays

Array : An Object which is an ordered collection of data items. These data items
could be
• primitive types.
• references to objects of a class.
Array : declaration and creation
Array : declaration and creation

int[ ] A ;
A = new int[4];
Array : declaration and creation

int[ ] A ;
A = new int[4];

Expression of type int


Manipulating the contents of array A

A has four variables of type int


• A[0] represent the first variable, A[1] the second
variable, ..., A[3] the last variable.
• Each A[i], for 0≤ i ≤3, can be treated as a single
independent variable.
Array : Accessing and Manipulating elements of an array
Array : Accessing and Manipulating elements of an array
Array : Accessing and Manipulating elements of an array
Array of Points
More on arrays

1.the number of elements in an array is called length of an


array.
2. array name.length returns the length of the array array
name.
3. For example, A.length will be equal to 3.
4. Length of an array object once created can never be
altered.
Array Syntax
double[ ] number;
double[ ] number = {1,2,3} ;
double[] numArray = new double[3];
String sArray[ ] = {"This", "is", "an", "array"};
Array
Arrays are predefined types of objects that
can hold a series of values
– An array uses an index to access a particular value
– No explicit constructor needed
– Some pre-defined variables e.g. “.length”
Array Implementation
Every time an array is initialized, using new, or by {… },
• a contiguous block of memory is assigned for it
• the array name (e.g numArray) is assigned the start address (In Java, this address
is the reference for this variable).
• numArray[0] is the first element
Printing an Array
class ArrayPrint
{
public static void main (String arg[])
{
double numbers[] = {1,2,3};
double numbers2[] = {1,2,3,4};
String s[] = {"This", "is", "an", "array"};
printArray (s,4);
}
public static void printArray (String[] arr, int length)
{ for(int j=0;j<length;j++)
System.out.println("Element "+j+"= "+arr[j]);
}
}
Array Length
Array objects have some predefined variables
e.g. length
String s[ ] = {"This", "is", "an", "array"};
System.out.println("Length of s: "+s.length);
Rainfall data - average
class Rainfall {
public static void main (String arg[])
{
double dailyRainFall[] = {12.3, 13.5, 4.2, 2.4, 1.1, 0, 10.8};
int i;
double average = 0;
for (i=0; i<7; i++)
{ average += dailyRainFall[i]; }
average /= 7;
System.out.println ("Average rain fall:"+ average + " mm");
// System.out.printf ("Average rain fall: %2.2f mm %n", average);
}
}
Finding the average
for (i=0; i<7; i++)
{ average += dailyRainFall[i]; }
average /= 7;
Everytime I have another day of rain, I need to change the number “7” in
my program

Instead, I can use


for (i=0; i<dailyRainFall.length; i++)
{ average += dailyRainFall[i]; }
average /= dailyRainFall.length;
class ArrayPrint
class ArrayPrint
{
public static void main (String arg[])
{
String s[ ] = {"This", "is", "a", "test", "array"};
printArray(s);
System.out.println( "s[0] length is: "+s[0].length() );
}
public static void printArray (String[] arr)
{ for(int j=0;j<arr.length;j++)
System.out.println("Element "+j+"= "+arr[j]);
}
// exercise: define lengthOfStringArray (String[] s)
}
Parallel Arrays
Say wish to record who got how many marks in the recent
midsem.
• One solution: use several arrays in parallel:
int[ ] regNum= {6016, 6024, 6078};
double[ ] midsemMarks = {61.7, 54 , 74.2 };
String[ ] name = {"Ali", “John",“Sheila"};
• Finding maximum marks?
Maximum Marks
public static double findMax (double numbers[])
{
double max = numbers[0];
for (int i=1; i<numbers.length; i++)
{ if (numbers[i] > max)
max = numbers[i];
}
return max;
}
But what if we want to know WHO got this maximum mark?
Can return the index of the maximum mark person instead.
Maximum Marks index
/** finds the index of the person with maximum marks */
public static int findMaxIndex (double numbers[]){
double max = numbers[0];
int index = 0;
for (int i=1; i<numbers.length; i++){
if (numbers[i] > max){
max = numbers[i];
index = i;
}
}
return index;
}
Parallel Arrays
Now we can use:
System.out.println ("Highest marks, by "+name[maxIndex]+ “
(Y"+regNum[maxIndex]+") = "+midsemMarks[maxIndex]);

BUT: What if we wish to sort the marks? How can we maintain the roll
numbers etc?
Student records
regNum= {6016, 6024, 6078};
midsemMarks = {61.7, 54 , 74.2 };
name = {"Ali",“John",“Sheila"};
In practice, parallel arrays are hard to maintain.
Better is to define an object STUDENT with data:
regNum, marks, and name, and define arrays of
the STUDENT object: Student[ ]
Arrays of Objects
Parallel array solution:
regNum= {6016, 6024, 6078};
midsemMarks = {61.7, 54 , 74.2 };
name = {"Ali", “John",“Sheila"};

In practice, parallel arrays are hard to maintain.


Better: define class STUDENT with attributes
- regNum,
- marks,
- name,
and define arrays of the STUDENT object: Student[ ]
Student Class: Attributes
public class Student
{
private String rollNum;
private String firstName;
private String midName;
private String lastName;
private int hostelNum;
private char wing;
private int roomNum;
private Date birthDate;
private Course[] courseList;
private char grade;
private double marks;
...
}
Other Classes used by “Student”

private Date birthDate;


Requires class “Date”. This is defined in separate file
Date.java in the same directory.
Similarly
private Course[] courseList;
Requires the class “Course”, defined in Course.java.
These three files constitute a “package”.
If they are in the same directory, Java automatically
recognizes them as a package
Student Class: Constructors
// Default constructor
public Student()
{
// initialise instance variables
birthDate = new Date();
courseList = new Course[MAX_COURSES];
}
/** Constructor with roll number */
public Student(String roll)
{
regNum = reg;
birthDate = new Date();
courseList = new Course[MAX_COURSES];
}
Batch midsem marks: Highest
Multidimensional Arrays
int[][] sqr = new int[5][5];
// this prints out the array
for (int r=0; r < sqr.length; r++) {
System.out.println(Arrays.toString( sqr[r]));
}
Note: Array elements get default values. E.g. numericals get zero.
Can also initialize multidim arrays:
int [] [] magicSquare = { {8, 1, 6} , {3, 5, 7}, {4, 9, 2} };

You might also like