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

Lecture 8 Arrays in Java

Arrays in Java

Uploaded by

mwaslam2303
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)
2 views

Lecture 8 Arrays in Java

Arrays in Java

Uploaded by

mwaslam2303
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/ 18

7/29/2020

IN2203

Fundamentals of Programming
(Java)

Instructor
Dr. Muhammad Waqar
muhammad.aslam@purescollege.ca

Arrays
• An array is a group of like-typed variables that are referred to by a common
name.
Tests
• Arrays of any type can be created and may have one or more dimensions.
• A specific element in an array is accessed by its index.
• Arrays offer a convenient means of grouping related information.
• A one-dimensional array is, essentially, a list of like-typed variables.
• To create an array, you first must create an array variable of the desired type.
The general form of a one-dimensional array declaration is

• type var-name[ ];
• int month_days[];

1
7/29/2020

Alternative Array Declaration Syntax


• There is a another form that may be used to declare an array. For example,
the following two declarations are equivalent:
Tests

• int al[] = new int[3];


• int[] a2 = new int[3];

• This alternative declaration form offers convenience when declaring several


arrays at the same time. For example,

• int[] nums, nums2, nums3; // create three arrays


• int nums[], nums2[], nums3[]; // create three arrays

Arrays
• Although this declaration (int month_days[]) establishes the fact that
month_days is an array variable, no array actually exists.
• The value of month_days is set to null,Tests
which represents an array with no
value.
• To link month_days with an actual, physical array of integers, you must
allocate one using new and assign it to month_days.
• new is a special operator that allocates memory.
• Once an array is created, its size is fixed. An array reference variable is used to
access the elements in an array using an index.

• array-var = new type[size];


• month_days = new int[12];
• int month_days[] = new int[12];

2
7/29/2020

Assigning values to arrays


• The statement int month_days[] = new int[12]; just declares an integer array
which can contain 12 integers.
Tests
• The values to this integer can be assigned by accessing its elements using
indices. For example

month_days[0] = 31 assigns value 31 to index 0 of array


month_days[1] = 28 assigns value 28 to index 1 of array

System.out.println(month_days[1]);

A simple program using Array


// Demonstrate a one-dimensional array.
class Array {
Tests {
public static void main(String args[])
int month_days[];
month_days = new int[12];
month_days[0] = 31; month_days[1] = 28; month_days[2] = 31;
month_days[3] = 30; month_days[4] = 31; month_days[5] = 30;
month_days[6] = 31; month_days[7] = 31; month_days[8] = 30;
month_days[9] = 31; month_days[10] = 30; month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}

3
7/29/2020

Another simple program using Array


import java.util.Scanner;

double[] myList = new double[10]; Tests

Scanner input = new java.util.Scanner(System.in);


System.out.print("Enter " + myList.length + " values: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();

Note: We use for loop for arrays because length of array is already known.

Practice Problem for taking Average


• Write a program which asks user to enter the total number of entries for
taking average.
Tests

• Declare an array with size of entries entered by user.

• Ask user to enter the actual numbers for which average has to be taken and
save it in an array using for loop

• Use another for loop to scan through array and calculate the sum and average

• Print average at the output.

4
7/29/2020

Code
System.out.print("Please specify total number of entrie:\t");
Scanner input = new Scanner(System.in);
int entries = input.nextInt(); Tests
double[] myList = new double[entries];
System.out.print("Enter " + myList.length + " values and press
enter after every value: ");
for (int i = 0; i < myList.length; i++){
myList[i] = input.nextDouble();}
int sum = 0;
for (int i = 0; i < myList.length; i++){
sum+= myList[i];}
double average = sum/myList.length;
System.out.print("Average is: \t" + average);

10

Array Initialization
• Arrays can be initialized when they are declared.
• An array initializer is a list of comma-separated expressions surrounded by
Tests
curly braces. The commas separate the values of the array elements.
• The array will automatically be created large enough to hold the number of
elements you specify in the array initializer. There is no need to use new.

class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}

10

5
7/29/2020

11

Practice Program

1- Initialize an Array month_days with month values as given in a previous


Tests
program (AutoArray Class).

2- Use Scanner class to ask user which month days he/she wants to know.

3- Display the month days after extracting from Array.

11

12

Practice Program Code


import java.util.Scanner;
public class MonthDays{
Tests
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("This program shows number of days of any month you enter.");
System.out.print("Please enter month number : ");
int month_number = input.nextInt();
System.out.println("The number of days in month "+ month_number + " are " +
month_days[month_number-1]);
}
}

12

6
7/29/2020

13

Practice Problem
Declare an array and initialize it with few values.

Tests
Use a for loop to scan through this array and find out the maximum value in this array.

13

14

Practice problem code


int [] myList = { 10, 15, 1, 7, 17, 4 , 2 , 8};

Tests
int max = myList[0];
for (int i = 1; i < myList.length; i++){
if (myList[i]>max)
max=myList[i];
}

System.out.print("Maximum is: \t" + max);

14

7
7/29/2020

15

Practice problem
Writing a program for shifting the elements one position to the left and filling the last
element with the first element:
Tests

15

16

foreach loop
• Java supports a convenient for loop, known as a foreach loop, which enables
you to traverse the array sequentially without using an index variable.
Tests
• For example, the following code displays all the elements in the array myList:

for (double e: myList) {


System.out.println(e);
}

• You can read the code as “for each element e in myList, do the following.”
Note that the variable, e, must be declared as the same type as the elements
in myList.

16

8
7/29/2020

17

Practice problem
Declare and initialize an array and use foreach loop to print all elements of array
in one line with a tab between the elements.
Tests

17

18

Copying Arrays
• To copy the contents of one array into another, you have to copy the array’s individual
elements into the other array.
• Often, in a program, you need to duplicate an array or a part of an array. In such cases
Tests
you could attempt to use the assignment statement (=), as follows:
list2 = list1;
• However, this statement does not copy the contents of the array referenced by list1
to list2, but instead merely copies the reference value from list1 to list2. After this
statement, list1 and list2 reference the same array

18

9
7/29/2020

19

Copying Arrays
• In Java, you can use assignment statements to copy primitive data type variables, but
not arrays.
• Assigning one array variable to another array variable actually copies one reference to
Tests
another and makes both variables point to the same memory location.
• There are three ways to copy arrays:

• Use a loop to copy individual elements one by one.


• Use the static arraycopy method in the System class.
• Use the clone method to copy arrays (will study after studying classes)

19

20

Using loop to Copy Arrays


• You can write a loop to copy every element from the source array to the
corresponding element
• in the target array. The following code, for instance, copies sourceArray to targetArray
Tests
using a for loop.

int[] sourceArray = {2, 3, 1, 5, 10};


int[] targetArray = new int[sourceArray.length];

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


targetArray[i] = sourceArray[i];
}

20

10
7/29/2020

21

Using arraycopy to Copy Arrays


• Another approach is to use the arraycopy method in the java.lang.System class to
copy arrays instead of using a loop. The syntax for arraycopy is:
• arraycopy(sourceArray, srcPos, targetArray, tarPos,
Tests length);

• The parameters srcPos and tarPos indicate the starting positions in sourceArray and
targetArray, respectively.
• The number of elements copied from sourceArray to targetArray is indicated by
length. For example, you can rewrite the loop using the following statement:
• System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

• The arraycopy method does not allocate memory space for the target array. The
target array must have already been created with its memory space allocated. After
the copying takes place, targetArray and sourceArray have the same content but
independent memory locations.

21

22

Passing Arrays to Methods


• When passing an array to a method, the reference of the array is passed to the
method.
• Just as you can pass primitive type values to Tests
methods, you can also pass arrays to
methods but there are important differences between passing the values of
variables of primitive data types and passing arrays.

• For an argument of a primitive type, the argument’s value is passed.


• For an argument of an array type, the value of the argument is a reference to an
array; this reference is passed to the method. Thus, if you change the array in the
method, you will see the change outside the method.
• Semantically, it can be best described as pass-by-sharing, that is, the array in the
method is the same as the array being passed.

22

11
7/29/2020

23

Example of Passing Arrays to Methods


public class Test {
public static void main(String[] args) {
int x = 1; // x represents an int value
Tests
int[] y = new int[10]; // y represents an array of int values
m(x, y); // Invoke m with arguments x and y
System.out.println("x is " + x);
System.out.println("y[0] is " + y[0]);
}
public static void m(int number, int[] numbers) {
number = 1001; // Assign a new value to number
numbers[0] = 5555; // Assign a new value to numbers[0]
}
}

23

24

Example of Passing Arrays to Methods


public class Test {
public static void main(String[] args) {
int x = 1; // x represents an int value
Tests
int[] y = new int[10]; // y represents an array of int values
m(x, y); // Invoke m with arguments x and y
System.out.println("x is " + x);
System.out.println("y[0] is " + y[0]);
}
public static void m(int number, int[] numbers) {
number = 1001; // Assign a new value to number
numbers[0] = 5555; // Assign a new value to numbers[0]
}
}

24

12
7/29/2020

25

Returning an Array from a Method


• When a method returns an array, the reference of the array is returned.
• You can pass arrays when invoking a method. A method may also return an array.
For example, the following method returns an array that is the reversal of another
Tests
array.

public static int[] reverse(int[] list) {


int[] result = new int[list.length];
j = result.length – 1;
for (int i = 0; i < list.length; i++) {
result[j] = list[i];
j--;
}
return result;
}

25

26

Returning an Array from a Method


• Write a program which uses a method to reverse elements of array. The return type
of method should be void and it should reverse elements of array using reference to
Tests
original array

26

13
7/29/2020

27

Searching Arrays
• Searching is the process of looking for a specific element in an array

• for example, discovering whether a certain score


Testsis included in a list of scores.

• Searching is a common task in computer programming. Many algorithms and data


structures are devoted to searching.

• Two commonly used approaches are, linear search and binary search.

27

28

The Linear Search


• The linear search approach compares the key element key sequentially with each
element in the array.
• It continues to do so until the key matches an element in the array or the array is
Tests
exhausted without a match being found.
• If a match is made, the linear search returns the index of the element in the array
that matches the key. If no match is found, the search returns -1.

public static int linearSearch(int[] list, int key) {


for (int i = 0; i < list.length; i++) {
if (key == list[i])
return i;
}
return -1;
}

28

14
7/29/2020

29

Practice Program using the Linear Search

Write a program which uses linear search method to find index of 6 in this array.
Tests
int[] list = {1, 4, 4, 2, 5, -3, 6, 2};

29

30

The Binary Search


• For binary search to work, the elements in the array must already be ordered.
• Assume that the array is in ascending order.
Tests
• The binary search first compares the key with the element in the middle of the
array. Consider the following three cases:

• If the key is less than the middle element, you need to continue to search for the
key only in the first half of the array.
• If the key is equal to the middle element, the search ends with a match.
• If the key is greater than the middle element, you need to continue to search for
the key only in the second half of the array.

30

15
7/29/2020

31

The Binary Search


public static int binarySearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
Tests
while (high >= low) {
int mid = (low + high) / 2;
if (key < list[mid])
high = mid - 1;
else if (key == list[mid])
return mid;
else
low = mid + 1;
}
return –low - 1; // Now high < low, key not found
}

31

32

Practice Program using the Binary Search

Write a program which uses binary search method to find index of 11 in this array.
Tests
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};

32

16
7/29/2020

33

Multi Dimensional Arrays


• In Java, multidimensional arrays are actually arrays of arrays.
• To declare a multidimensional array variable, specify each additional index
Tests
using another set of square brackets

• int twoD[][] = new int[4][5];

• This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is


implemented as an array of arrays of int.
• The graphical visualization of this array is given on the next slide.

33

34

Multi Dimensional Arrays

Tests

34

17
7/29/2020

35

Multi Dimensional Arrays


• When you allocate memory for a multidimensional array, you need only
specify the memory for the first (leftmost) dimension. You can allocate the
remaining dimensions separately. For example
Tests

int twoD[][] = new int[4][];


twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];

35

36

Multi Dimensional Arrays


• It is possible to initialize multidimensional arrays. To do so, simply enclose
each dimension’s initializer within its own set of curly braces.
Tests

• double m[][] = {
• { 0*0, 1*0, 2*0, 3*0 },
• { 0*1, 1*1, 2*1, 3*1 },
• { 0*2, 1*2, 2*2, 3*2 },
• { 0*3, 1*3, 2*3, 3*3 }
• };

• Write a program to create this multi dimensional array and print its element at
3rd row and 2nd column.

36

18

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy