0% found this document useful (0 votes)
11 views

lec 7- Arrays_F

Lecture 7 covers the fundamentals of arrays, including their definition, advantages, declaration, initialization, and usage in Java. It also discusses one- and two-dimensional arrays, the concept of indices, and various algorithms for manipulating arrays, such as insertion and removal of elements. Additionally, the lecture introduces 'for each' loops for traversing arrays and emphasizes the importance of arrays in efficient data handling.

Uploaded by

Ahmed Mohamed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

lec 7- Arrays_F

Lecture 7 covers the fundamentals of arrays, including their definition, advantages, declaration, initialization, and usage in Java. It also discusses one- and two-dimensional arrays, the concept of indices, and various algorithms for manipulating arrays, such as insertion and removal of elements. Additionally, the lecture introduces 'for each' loops for traversing arrays and emphasizes the importance of arrays in efficient data handling.

Uploaded by

Ahmed Mohamed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Lecture 7 – Array

Dr Nora El Rahsidy
Objectives:
1. Learn about one- and two-dimensional arrays and when to
use them
2. Learn the syntax for declaring and initializing arrays and how
to access array’s size and elements
3. Discuss “for each” loops
4. Learn several array algorithms

9-2
What is an Array
• Array is a data structure that stores a fixed-size sequential
collection of elements of the same type.
• An array is a block of consecutive memory locations that hold
values of the same data type.
• Individual locations are called array’s elements.
• When we say “element” we often mean the value stored in that
element.
1.39 1.69 1.74 0.0 An array of
doubles

9-3
What is an Array (cont’d)
• Rather than treating each element as a separate named variable,
the whole array gets one name.
• Specific array elements are referred to by using array’s name and
the element’s number, called index or subscript.

1.39 1.69 1.74 0.0


c[0] c[1] c[2] c[3] c is array’s
name

9-4
Advantages of using array
•Efficient Storage: Arrays provide a contiguous block of memory to store elements of the same type. This
results in efficient memory allocation and access, as elements are stored sequentially.
•Random Access: Elements in an array can be accessed randomly using their index. This direct access
makes retrieving and modifying elements quick and easy, with a time complexity of O(1).
•Performance: Array operations like element access, insertion, and deletion have predictable and efficient
time complexities. This predictability allows for better performance in algorithms and data processing tasks.
•Iterating Over Elements: Arrays support efficient iteration through elements using loops, making it easy to
process all elements in the collection sequentially.
•Multi-dimensional Support: Java arrays can be multidimensional, allowing you to create arrays of arrays
(e.g., matrices). This feature is beneficial for representing complex data structures.
•Ease of Implementation: Arrays are straightforward to implement and understand, making them an
excellent choice for a wide range of applications, from basic data storage to complex algorithms.
Indices (Subscripts)
• In Java, an index is written within square brackets following array’s
name (for example, a[k]).

• Indices start from 0; the first element of an array a is referred to as


a[0] and the n-th element as a[n-1].

• An index can have any int value from 0 to array’s length - 1.

9-6
Indices (cont’d)
• We can use as an index an int variable or any expression that
evaluates to an int value. For example:

a [3]
a [k]
a [k - 2]
a [ (int) (6 * Math.random()) ]

9-7
Indices (cont’d)
• In Java, an array is declared with fixed length that cannot be changed.

• Java interpreter checks the values of indices at run time and throws

ArrayIndexOutOfBoundsException if an index is negative or if it is

greater than the length of the array - 1.

9-8
Why Do We Need Arrays?
• The power of arrays comes from the fact that the value of an index
can be computed and updated at run time.

No arrays: With arrays:

int sum = 0; int n = 1000;


sum += score0; int sum = 0;
1000 sum += score1;
times! … for (int k = 0; k < n; k++)
sum += score999; sum += scores[k];

9-9
Why Arrays? (cont’d)
• Arrays give direct access to any element — no need to scan the
array.
No arrays: With arrays:

if (k == 0) display (scores[k]);
1000 display (score0);
times! else if (k == 1)
display (score1);
else
… // etc.

9-10
Arrays as Objects
• In Java, an array is an object. If the type of its elements is anyType,
the type of the array object is anyType[ ].
• Array declaration:

someType [ ] arrName;

9-11
Arrays as Objects (cont’d)
• As with other objects, the declaration creates only a reference,
initially set to null. An array must be created before it can be used.
• One way to create an array:

arrName = new someType [n] ; Brackets,


not parens!

9-12
Declaration and Initialization
• When an array is created, space is allocated to hold its elements.
If a list of values is not given, the elements get the default values.
For example:
length 10,
all values
int scores [] = new int [10] ; set to 0

string words [] = new String length 10000,


[10000]; all values set to
null

9-13
Initialization (cont’d)
• An array can be declared an initialized in one statement. For
example:
double [ ] gasPrices = { 3.05, 3.17, 3.59 };
String [ ] cities = {"Atlanta", "Boston", "Cincinnati" };

9-14
Initialization (cont’d)
• Otherwise, initialization can be postponed until later. For
example:
Not yet
String [ ] words; initialized
...
string words [] = new String [ kboard.readInt() ];
Not yet
private double[ ] gasPrices; initialized

double gasPrices [] = new double[ ] { 3.05, 3.17, 3.59 };

9-15
Array’s Length

• The length of an array is determined when that array is created.

• The length is either given explicitly or comes from the length of the
{…} initialization list.

• The length of an array arrName is referred to in the code as


arrName.length.

• length is like a public field (not a method) in an array object.


9-16
Initializing Elements

• Unless specific values are given in a {…} list, all the elements are
initialized to the default value: 0 for numbers, false for booleans,
null for objects.

• If its elements are objects, the array holds references to objects,


which are initially set to null.

• Each object-type element must be initialized before it is used.

9-17
Initializing Elements (cont’d)
• Example:
Array not
Color[ ] pens; created yet
... Array is created;
pens = new Color [ 3 ]; all three elements
are set to null
...
pens [0] = Color.BLUE;
pens [1] = new Color (15, 255, 255); Now all three
pens [2] = g.getColor(); elements are
initialized

9-18
Add elements to array and printing it
public static void main(String[] args)
{
// Declare and initialize an array of integers
int size = 5;
int[] numbers = new int[size];
// Adding values to the array using a for loop
for (int i = 0; i < size; i++)
{
numbers[i] = i * 10; // Assigning values (e.g., 0, 10, 20, 30, 40) to the array
}
// Printing the elements in the array
System.out.println("Elements in the array:");
for (int i = 0; i < size; i++)
{
System.out.println("Element at index " + i + ": " + numbers[i]);
}
} 9-19
Two-Dimensional Arrays
• 2-D arrays are used to represent tables, matrices, game
boards, images, etc.
• An element of a 2-D array is addressed using a pair of
indices, “row” and “column.” For example:

board [ r ] [ c ] = 'x';

9-20
2-D Arrays: Declaration
// 2-D array of char with 5 rows, 7 cols:
char[ ] [ ] letterGrid = new char [5][7];

// 2-D array of Color with 1024 rows, 768 cols:


Color[ ] [ ] image = new Color [1024][768];

// 2-D array of double with 2 rows and 3 cols:


double [ ] [ ] sample =
{ { 0.0, 0.1, 0.2 },
{ 1.0, 1.1, 1.2 } };

9-21
2-D Arrays: Dimensions
• In Java, a 2-D array is basically a 1-D array of 1-D arrays, its rows.
Each row is stored in a separate block of consecutive memory
locations.
• If m is a 2-D array, then m[k] is a 1-D array, the k-th row.
• m.length is the number of rows.
• m[k].length is the length of the k-th row.

9-22
Dimensions (cont’d)
• Java allows “ragged” arrays, in which different
rows have different lengths.
• In a rectangular array, m[0].length can be used
to represent the number of columns.

“Ragged” array: Rectangular array:

m.length m.length

m[3].length m[0].length
9-23
2-D Arrays and Nested Loops
• A 2-D array can be traversed using nested
loops:

for (int r = 0; r < m.length; r++)


{
for (int c = 0; c < m[0].length; c++)
{
... // process m[ r ][ c ]
}
}

9-24
“Triangular” Loops
• “Transpose a matrix” idiom:

int n = m.length;

for (int r = 1; r < n; r++)


{
The total number of
for (int c = 0; c < r; c++) iterations through the
{ inner loop is:
double temp = m [ r ][ c ];
m [ r ][ c ] = m [ c ][ r ]; 1 + 2 + 3 + ... + (n-1) =
n (n - 1) / 2
m [ c ][ r ] = temp;
}
}
9-25
Example on 2D array
• Initializing 2D array
“For Each” Loop
• Introduced in Java 5
• Works with standard arrays as well as Java “collections.”
• Convenient for traversing arrays
• Replaces iterators for collections

9-27
“For Each” Loop: Example 1
int [ ] scores = { ... };
...
int sum = 0;

for (int s : scores)


{
sum += s;
Basically the same as:
}
...
for (int i = 0; i < scores.length; i++)
{
int s = scores[i];
sum += s;
}

9-28
“For Each” Loop: Example 2
String[ ] words = new String [10000];

... // read words from a file

for (String str : words)


{
System.out.println(str); // display str
}
Basically the same as:

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


{
String str = words [i];
System.out.println(str);
}
9-29
“For Each” Loop (cont’d)
• You cannot add or remove elements within a “for each” loop.
• You cannot change values of elements within a “for each” loop,
whether they are of primitive data types or references to objects.
• However, you can change an object, if it is mutable, by calling a
mutator method on that object.

9-30
“For each” loops with 2-D Arrays
• It is possible to use nested “for each” loops
with 2-D arrays:

for (int[ ] row : m)


{
for (int x : row)
{
... // process x
}
}

9-31
Inserting a Value into a Sorted Array (Task)

• Given: an array, sorted in ascending order. The number of values

stored in the array is smaller than array’s length: there are some

unused elements at the end.

• Task: insert a value while preserving the order.

9-32
Inserting a Value (cont’d)
1. Find the right place to insert:
5 Can be combined
1 1 2 3 8 13 together in one
loop: look for the
2. Shift elements to the right, place to insert
starting from the last one: while shifting.
5
1 1 2 3 8 13
3. Insert the value in its proper place:

1 1 2 3 5 8 13

9-33
Inserting a Value (cont’d)
// Returns true if inserted successfully, false otherwise
public boolean insert(double[ ] arr, int count, double value)
{
if (count >= arr.length)
return false;

int k = count - 1;
while ( k >= 0 && arr [ k ] > value )
{
arr [ k + 1 ] = arr [ k ];
k--;
}
arr [ k + 1] = value;

return true;
}
9-34
Insertion process

• Method name insert

• It takes an array of `double` values (`arr`), an integer `count` representing

the current number of elements in the array, and a `double` value `value` to

insert into the array.

• The method returns a boolean value: `true` if the insertion is successful

and `false` otherwise.


Insertion process cont.'s
• The method first checks if there is enough space in the array to insert a new element. If the current
count is equal to or greater than the length of the array (`count >= arr.length`), it returns `false`,
indicating that the insertion cannot be done.

• If there is space, the method proceeds to insert the new value into the array.

• It starts by initializing an index `k` to `count - 1`, which is the index of the last element in the current
array (before insertion).

• It then iterates from index `k` towards the beginning of the array while `k` is greater than or equal to
0 and the value at index `k` is greater than the value to be inserted.

• During each iteration, it shifts elements to the right (moving the elements one position to the right) to
make space for the new value.

• Once the loop ends, the new value is inserted at index `k + 1`, maintaining the order of elements in
the array.
Removing a Value
1. Shift elements to the left, starting at the given
position and proceeding from left to right:

Step 1 Step 2 ...

1 1 2 3 5 8 13

9-37
Removing a Value (cont’d)
// Returns true if removed the k-th element
// successfully, false otherwise
public boolean remove(double[ ] arr, int count, int k)
{
if (k >= count)
return false;

while (k < count)


{
arr [ k ] = arr [ k + 1];
k++;
}
return true;
}

9-38
Method signature

• The method is named `remove`.

• It takes an array of `double` values (`arr`), an integer `count` representing the current

number of elements in the array, and an integer `k` representing the index of the element

to be removed.

• The method returns a boolean value: `true` if the removal is successful and `false`

otherwise.
Removal logic
• The method first checks if the index `k` is within the bounds of the array. If `k` is greater than or equal
to `count`, it returns `false`, indicating that the removal cannot be done.

• If `k` is a valid index, the method proceeds to remove the element at index `k`.

• It starts a loop from the specified index `k` and continues until `k` is less than `count`.

• During each iteration, it shifts elements to the left by copying the value from the next index (`k + 1`) to
the current index (`k`).

• This shifting effectively removes the element at index `k`.

• After shifting all elements to the left, the method returns `true` to indicate that the removal was
successful.
Examples
Finding the Maximum Element in an Array
Examples
Summing all Element in an Array
Examples (cont’d):
Finding the Average of Elements in an Array
Examples (cont’d):
Initializing a String Array and Printing Elements
Examples (cont’d):
Finding the Sum of Diagonal Elements in a 2D Array
Review:
• Why are arrays useful?
• What types of elements can an array have?
• How do we refer to an array’s element in Java?
• What happens if an index has an invalid value?
• How do we refer to the length of an array?

9-46
Review (cont’d):
• Can we resize an array after it has been created?
• Are arrays in Java treated as primitive data types or as objects?
• What values do array’s elements get when the array is created?
• Are the array’s elements copied when an array is passed to a
method?
• Can a method return an array?

9-47
Review (cont’d):
• Name a few applications of two-dimensional arrays.
• If m is a 2-D array of ints, what is the type of m[0]?
• How do we get the numbers of rows and cols in a 2-D array?
• Describe an algorithm for inserting a value into a sorted array.

9-48
Thanks!
Do you have any questions?

You might also like