0% found this document useful (0 votes)
27 views28 pages

Array

The document provides an introduction to arrays, explaining their purpose, declaration, and initialization in programming. It covers accessing elements, copying arrays, and performing operations such as finding the highest value and summing elements. Additionally, it discusses 2-D arrays and practical applications for storing and processing data efficiently.

Uploaded by

Aliyu Faruk
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)
27 views28 pages

Array

The document provides an introduction to arrays, explaining their purpose, declaration, and initialization in programming. It covers accessing elements, copying arrays, and performing operations such as finding the highest value and summing elements. Additionally, it discusses 2-D arrays and practical applications for storing and processing data efficiently.

Uploaded by

Aliyu Faruk
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/ 28

Array

Introduction to Arrays
• We have used Primitive Data types to store attributes of a class
• int, double, Boolean, String
• Primitive variables are designed to hold only one value at a time.
• Arrays allow us to create a collection of values of the same type.
• An array can store any type of data but only one type of data at a
time.
• An array is a list of data elements
Introduction to Arrays
• An array is an object so it needs an object reference..
int[] numbers;

The variable number is an array


Data type for the elements

• The next step creates the array and assigns its


address to the numbers variable
numbers = new int[6];

Constructor for the array


Dimension of the array
Example of Array

Numbers

0 0 0 0 0 0
index 0 index 1 index 2 index 3 index 4 index 5
Array element values are initialised to 0.
Array indexes always start at 0.
Declaring Arrays

• It is possible to declare an array variable and


create it in the same statement.
int[] numbers = new int[6];

• Arrays may be of any type.


float[] temperatures = new float[100];
char[] letters = new char[41];
long[] units = new long[50];
double[] sizes = new double[1200];

• We can even have arrays of Objects.


Creating an Array
• The array size must be a non-negative number.
• It may be a literal value, a constant, or variable.
final int ARRAY_SIZE = 6;
int[] numbers = new int[ARRAY_SIZE];
• Once created, an array size is fixed and cannot be
changed.
Accessing the elements of the Array
• The elements are accessing by:
• The name of the variable
• The index of the element

• numbres[0] = 20;
Numbers

20 0 0 0 0 0
index 0 index 1 index 2 index 3 index 4 index 5
Copying Arrays
• This is not the way to copy an array.
int[] array1 = { 2, 4, 6, 8, 10 };
int[] array2 = array1; // This does not copy
array1.

2 4 6 8 10

array1 holds an
Address
address to the array

array2 holds an
Address
address to the array
Copying Arrays
• You cannot copy an array by merely assigning one reference variable
to another.
• You need to copy the individual elements of one array to another.
int[] firstArray = {5, 10, 15, 20, 25 };
int[] secondArray = new int[5];
for (int i = 0; i < firstArray.length; i++)
secondArray[i] = firstArray[i];
• This code copies each element of firstArray to the
corresponding element of secondArray.
Accessing elements of an Array
• For loops are very useful for visiting the elements of an array
• for loops help us to move from one element to the next

QUESTION
• What elements does the data array contain after the following
statements?

double[] data = new double[10];


for (int i = 0; i < 10; i++) {
data[i] = i * i;
}
QUESTION
What do the following program segments print?
Or, if there is an error, describe the error and specify whether it is
detected at compile-time or at run-time.

1. double[] a = new double[10];


System.out.println(a[0]);
2. double[] b = new double[10];
System.out.println(b[10]);
3. double[] c;
System.out.println(c[0]);
Array Length
• Arrays are objects and provide a public field named length that is
a constant that can be tested.
double[] temperatures = new double[31];
• The length of this array is 31.
• The length of an array can be obtained via its length constant.
int size = temperatures.length;
• The variable size will contain 31.
Array Length
• The array length attribute is quite useful
• length can be used to provide automatic bounding

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


{
System.out.println("Temperature " + i ": "
+ temperatures[i]);
}
Array Initialisation
• Arrays can be initialised

• int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}

• days is an array of 12 elements


days[0]  31
days[1] 28
...
Useful Arrays Operations
• Comparing two arrays
• Calculate the Total
• Get the Highest Value
Comparing Arrays
• The == operator determines only whether array
references point to the same array object.
• To compare the contents of an array, every element of
the array must be checked

• If arrays are of different size the arrays are not


identical
• If the arrays are of the same size compare each
element until we get to the end or the element in
position “i” of both arrays is different
Example
int[] firstArray = { 2, 4, 6, 8, 10 };
int[] secondArray = { 2, 4, 6, 8, 10 };
boolean arraysEqual = true;
int i = 0;
if (firstArray.length != secondArray.length)
arraysEqual = false;
while (arraysEqual && i < firstArray.length)
{
if (firstArray[i] != secondArray[i])
arraysEqual = false;
i++;
}
if (arraysEqual)
System.out.println("The arrays are equal.");
else
System.out.println("The arrays are not equal.");
Find the Highest Value
• Finding the Highest Value

int highest = numbers[0];


for (int i = 1; i < numbers.length; i++)
{
if (numbers[i] > highest)
highest = numbers[i];
}
Sum all the numbers in the array
• Summing Array Elements:
int total = 0;
for (int i = 0; i < units.length; i++)
total += units[i];
Case Study 1
• We want a program that stores the hours worked by 5 employees
• Assuming that all the employees are payed the same we want to
calculate the gross salary of each employee
Case Study 2
• Temperature at Wheatley Campus is read every two hours and the
last 12 readings are stored in an array. Given the reading, we want
to calculate the average and get the highest and lowest
temperatures
Partially Filled Arrays
• Typically, if the amount of data that an array must hold is unknown:
• size the array to the largest expected number of elements.
• use a counting variable to keep track of how much valid data is in the array.

int[] array = new int[100];


int count = 0;

System.out.print("Enter a number or -1 to quit: ");


number = inp.nextInt();
while (number != -1 && count <= 99)
{
array[count] = number;
count++;
System.out.print("Enter a number or -1 to quit: ");
number = inp.nextInt();
}

Question
• Declare an array named num that contains 10 floats to the values
1.0, 2.0, .., 10.0.
• Write an expression that prints the first element of num.
• Write an assignment statements that assigns 100.00 to the last
element in num.
• Write a loop to print all of the element of num.
2-D Arrays
• Array can have more than one dimension
• A Table with columns and rows is a 2 dimensional array
• The marks of all the students for 4 modules

• Definition of a 2-D array variable

double [][] marks = new int[20] [4];

Rows Columns
2-D representation
• It is a table
• First dimension: row
• Second dimension: columns

0 1 2 3
0
marks[2][1] = 55;
1

2 55

19
Accessing 2-D arrays
Number of rows
• Initialisation of the marks array

for (int row = 0; row < marks.length; row++)


{
for (int col = 0; col < marks[row].length; col++)
{
System.out.print("Enter a mark: ");
marks[row][col] = keyboard.nextDouble();
}
}

Number of columns in that row


Your work in the practical
Write a program to read 10 students name, assessment components
which is coursework and exam. Both of this component marks
entered base 100. Calculate the average marks for the subject and
display the average marks and the grade. The grading list as shown
bellow:
Marks range Grade
80 .. 100 A
60 .. 79 B
50 .. 59 C
0 ..49 FAIL
Summary
• Why we need array
• Store large amount of information of the same type
• How we can use array in a program
• User-defined data type and variables
• Loops and arrays
• We need loops to transverse an array

You might also like