0% found this document useful (0 votes)
42 views17 pages

DSA Lab 05 SPRING 2022 SE

The document discusses passing arrays as parameters to methods in Java and returning arrays from methods. It provides examples of passing an integer array and returning a string array from methods. It also discusses generating and returning random number arrays from methods.

Uploaded by

Mehmood Sheikh
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)
42 views17 pages

DSA Lab 05 SPRING 2022 SE

The document discusses passing arrays as parameters to methods in Java and returning arrays from methods. It provides examples of passing an integer array and returning a string array from methods. It also discusses generating and returning random number arrays from methods.

Uploaded by

Mehmood Sheikh
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/ 17

USMAN INSTITUTE OF TECHNOLOGY

CS211 DATA STRUCTURES & ALGORITHMS


LAB 05
SPRING 2022

Name : _________________________________________
Roll No. : _________________ Section : ________________
Date : _________________________________________
Remarks : _________________________________________
Signature : _________________________________________
Lab 05 – Working with Advance applications of Arrays, operations on
April 20, 2022 arrays using functions in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________

Experiment No. 05
Lab 05 – Working with Advance applications of Arrays, operations on arrays using
functions in JAVA.

Introduction
In previous lab we have done with the foundations of array and its concepts. In this lab we use the
advance concepts and its applications.

Passing Array To The Method In Java


Arrays can be passed to other methods just like how you pass primitive data type’s arguments. To pass an
array as an argument to a method, you just have to pass the name of the array without square brackets. The
method prototype should match to accept the argument of the array type.

Given below is the method prototype


void method_name (int [] array);
This means method_name will accept an array parameter of type int. So if you have an int array named
myarray, then you can call the above method as follows:

method_name (myarray);
The above call passes the reference to the array myarray to the method ‘method_name’. Thus, the changes
made to myarray inside the method will reflect in the calling method as well.

Unlike in C/C++, you need not pass the length parameter along with array to the method as all Java arrays
have a property ‘length’. However, it might be advisable to pass several elements in case only a few
positions in the array are filled.

Example 5.1: Program demonstrates the passing of an array as a parameter to the function.

public class Main


{
//method to print an array, taking array as an argument
private static void printArray(Integer[] intArray){
System.out.println("Array contents printed through method:");
//print individual elements of array using enhanced for loop
for(Integer val: intArray)
System.out.print(val + " ");
}
public static void main(String[] args) {
//integer array
Integer[] intArray = {10,20,30,40,50,60,70,80};

//call printArray method by passing intArray as an argument


printArray(intArray);
}}
Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 1
Algorithms
Lab 05 – Working with Advance applications of Arrays, operations on
April 20, 2022 arrays using functions in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


Output:

In the above program, an array is initialized in the main function. Then the method printArray is called to
which this array is passed as an argument. In the printArray method, the array is traversed and each element
is printed using the enhanced for loop.

Let us take another example of passing arrays to methods. In this example, we have implemented two
classes. One class contains the calling method main while the other class contains the method to find the
maximum element in the array.

So, the main method calls the method in another class by passing the array to this method find_max. The
find_max method calculates the maximum element of the input array and returns it to the calling function.

Example 5.2: Program that has function find_max() which can find the max value from the given array.

class maxClass{
public int find_max(int [] myarray) {
int max_val = 0;
//traverse the array to compare each element with max_val
for(int i=0; i<myarray.length; i++ ) {
if(myarray[i]>max_val) {
max_val = myarray[i];
}
}
//return max_val
return max_val;
}
}
public class Main
{
public static void main(String args[]) {
//input array
int[] myArray = {43,54,23,65,78,85,88,92,10};
System.out.println("Input Array:" + Arrays.toString(myArray));

//create object of class which has method to find maximum


maxClassobj = new maxClass();
//pass input array to find_max method that returns maximum element
System.out.println("Maximum value in the given array
is::"+obj.find_max(myArray));
} }
Output:

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 2
Algorithms
Lab 05 – Working with Advance applications of Arrays, operations on
April 20, 2022 arrays using functions in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


How to Return An Array In Java
Apart from all the primitive types that you can return from Java programs, you can also return references
to arrays.

While returning a reference to an array from a method, you should keep in mind that:

1. The data type that returns value should be specified as the array of the appropriate data type.
2. The returned value from a method is the reference to the array.
3. The array is returned from a method in the cases where you need to return multiple values of the
same type from a method. This approach becomes useful as Java doesn’t allow returning multiple
values.

Example 5.3: Program returns a string array from a method.

import java.util.*;
public class Main
{
public static String[] return_Array() {
//define string array
String[] ret_Array = {"Java", "C++", "Python", "Ruby", "C"};
//return string array
return ret_Array;
}

public static void main(String args[]) {


//call method return_array that returns array
String[] str_Array = return_Array();
System.out.println("Array returned from method:" + Arrays.toString(str_Array));

}
}

Output:

The above program is an example of returning an array reference from a method. The ‘return_array’ method
is declared an array of strings ‘ret_Array’ and then simply returns it. In the main method, the return value
from the return_array method is assigned to the string array and then displayed.

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 3
Algorithms
Lab 05 – Working with Advance applications of Arrays, operations on
April 20, 2022 arrays using functions in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________

Example 5.4: Program that has an array having random elements, using a function.

public class Main


{
public static void main(String[] args)
{
final int N = 10; // number of random elements

// Create an array
int[] random_numbers;

// call create_random method that returns an array of random numbers


random_numbers = create_random(N);
System.out.println("The array of random numbers:");
// display array of random numbers
for (int i = 0; i <random_numbers.length; i++)
{
System.out.print(random_numbers[i] + " ");
}
}

public static int[] create_random(int N)


{
//Create an array of size N => number of random numbers to be generated
int[] random_array = new int[N];

//generate random numbers and assign to array


for (int i = 0; i <random_array.length; i++)
{
random_array[i] = (int) (Math.random() * 10);
}
//return array of random numbers
return random_array;
}
}

Output:

The following program provides another example of returning an array from a method. Here, we use an
integer array that is used to store the computed random numbers and then this array is returned to the caller.

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 4
Algorithms
Lab 05 – Working with Advance applications of Arrays, operations on
April 20, 2022 arrays using functions in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


Important Methods for Java Array
The following are few important methods for Java Array.

Sno. Required Code


String[] aArray = new String[5];
String[] bArray = {"a","b","c", "d", "e"};
1 Declare an array String[] cArray = new
String[]{"a","b","c","d","e"};

int[] intArray = { 1, 2, 3, 4, 5 };
String intArrayString = Arrays.toString(intArray);

// print directly will print reference value


2 Print an array in Java System.out.println(intArray);
// [I@7150bd4d

System.out.println(intArrayString);
// [1, 2, 3, 4, 5]
String[] stringArray = { "a", "b", "c", "d", "e"
};
Create an ArrayList from an ArrayList<String> arrayList = new
3 ArrayList<String>(Arrays.asList(stringArray));
array
System.out.println(arrayList);
// [a, b, c, d, e]
String[] stringArray = { "a", "b", "c", "d", "e"
};
Check if an array contains a boolean b =
4
certain value Arrays.asList(stringArray).contains("a");
System.out.println(b);
// true
int[] intArray = { 1, 2, 3, 4, 5 };
int[] intArray2 = { 6, 7, 8, 9, 10 };
5 Concatenate two arrays // Apache Commons Lang library
int[] combinedIntArray =
ArrayUtils.addAll(intArray, intArray2);
6 Declare an array inline method(new String[]{"a", "b", "c", "d", "e"});
//containing the provided list of elements
//Apache common lang
Joins the elements of the String j = StringUtils.join(new String[] { "a",
7 provided array into a single "b", "c" }, ", ");
String System.out.println(j);
//a, b, c

String[] stringArray = { "a", "b", "c", "d", "e"


};
ArrayList<String> arrayList = new
Convert an ArrayList to an ArrayList<String>(Arrays.asList(stringArray));
8 String[] stringArr = new String[arrayList.size()];
array
arrayList.toArray(stringArr);
for (String s : stringArr)
System.out.println(s);
Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 5
Algorithms
Lab 05 – Working with Advance applications of Arrays, operations on
April 20, 2022 arrays using functions in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


Set<String> set = new
HashSet<String>(Arrays.asList(stringArray));
9 Convert an array to a set System.out.println(set);
//[d, e, b, c, a]
int[] intArray = { 1, 2, 3, 4, 5 };
ArrayUtils.reverse(intArray);
10 Reverse an array System.out.println(Arrays.toString(intArray));
//[5, 4, 3, 2, 1]

int[] intArray = { 1, 2, 3, 4, 5 };
int[] removed = ArrayUtils.removeElement(intArray,
3);//create a new array
System.out.println(Arrays.toString(removed));
One more - convert int to byte array
11 Remove element of an array byte[] bytes =
ByteBuffer.allocate(4).putInt(8).array();

for (byte t : bytes) {


System.out.format("0x%x ", t);
}

PERFORMING SEARCHING, INSERT AND DELETE OPERATION ON


ARRAY
As we know that array is the type of collections and certain operations can be performing on an array
such as:
1. Traversing
2. Search
3. Insert
4. Delete
5. Append
6. Update

SEARCH AN ELEMENT IN UNSORTED ARRAY

In this case, an array is given and the task is to find the certain element from the array. If the desired element
found in the array it will return the position otherwise it will return that the key has not found.

Example 5.5: Program that can help in searching a key element from an unsorted array.

class Main
{
// Function to implement search operation
static int findElement(int arr[], int n,int key)
{
for (int i = 0; i < n; i++)
if (arr[i] == key)
Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 6
Algorithms
Lab 05 – Working with Advance applications of Arrays, operations on
April 20, 2022 arrays using functions in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


return i;

return -1;
}

// Driver Code
public static void main(String args[])
{
int arr[] = {12, 34, 10, 6, 40};
int n = arr.length;

// Using a last element as search element


int key = 40;
int position = findElement(arr, n, key);

if (position == - 1)
System.out.println("Element not found");
else
System.out.println("Element Found at Position: "
+ (position + 1));
}
}
Output:

INSERT AT THE END OF ARRAY


In an unsorted array, the insert operation is faster as compared to a sorted array because we don’t have to
care about the position at which the element is to be placed. But generally when we say insert it means that
we want to add an element in a certain location.

Example 5.6: Program to implement insert operation in an unsorted array.

class Main
{
// Function to insert a given key in the array. This function returns n+1
// if insertion is successful, else n.
static int insertSorted(int arr[], int n, int key, int capacity)
{

// Cannot insert more elements if n is already more than or equal to


// capacity
if (n >= capacity)
return n;

arr[n] = key;

return (n + 1);
}
Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 7
Algorithms
Lab 05 – Working with Advance applications of Arrays, operations on
April 20, 2022 arrays using functions in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________

// Driver Code
public static void main (String[] args)
{
int[] arr = new int[20];
arr[0] = 12;
arr[1] = 16;
arr[2] = 20;
arr[3] = 40;
arr[4] = 50;
arr[5] = 70;
int capacity = 20;
int n = 6;
int i, key = 26;

System.out.print("Before Insertion: ");


for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");

// Inserting key
n = insertSorted(arr, n, key, capacity);

System.out.print("\n After Insertion: ");


for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
}
}

Output:

DELETING KEY ELEMENT FROM THE ARRAY


In the delete operation, the element to be deleted is searched using the linear search, and then delete
operation is performed followed by shifting the elements.

Example 5.7: Program to implement delete operation in an unsorted array.

class Main
{
// function to search a key to
// be deleted
static int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 8
Algorithms
Lab 05 – Working with Advance applications of Arrays, operations on
April 20, 2022 arrays using functions in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________

return -1;
}

// Function to delete an element


static int deleteElement(int arr[], int n, int key)
{
// Find position of element to be
// deleted
int pos = findElement(arr, n, key);

if (pos == -1)
{
System.out.println("Element not found");
return n;
}

// Deleting element
int i;
for (i = pos; i< n - 1; i++)
arr[i] = arr[i + 1];

return n - 1;
}

// Driver Code
public static void main(String args[])
{
int i;
int arr[] = {10, 50, 30, 40, 20};

int n = arr.length;
int key = 30;

System.out.println("Array before deletion");


for (i=0; i<n; i++)
System.out.print(arr[i] + " ");

n = deleteElement(arr, n, key);

System.out.println("\n\nArray after deletion");


for (i=0; i<n; i++)
System.out.print(arr[i]+" ");
}
}

Output:

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 9
Algorithms
Lab 05 – Working with Advance applications of Arrays, operations on
April 20, 2022 arrays using functions in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


SEARCH AN ELEMENT IN SORTED ARRAY
In a sorted array, the search operation can be performed by using binary search.

Example 5.8: Program to implement binary search in a sorted array.

class Main {
// function to implement
// binary search
static int binarySearch(int arr[], int low, int high, int key)
{
if (high < low)
return -1;

/*low + (high - low)/2;*/


int mid = (low + high) / 2;
if (key == arr[mid])
return mid;
if (key > arr[mid])
return binarySearch(arr, (mid + 1), high, key);
return binarySearch(arr, low, (mid - 1), key);
}

/* Driver Code*/
public static void main(String[] args)
{
int arr[] = { 5, 6, 7, 8, 9, 10 };
int n, key;
n = arr.length - 1;
key = 10;

System.out.println("Index: " + binarySearch(arr, 0, n, key));


}
}

Output:

INSERT OPERATION IN SORRTED ARRAY


In a sorted array, a search operation is performed for the possible position of the given element by using
Binary search and then insert operation is performed followed by shifting the elements. And in an unsorted
array, the insert operation is faster as compared to the sorted array because we don’t have to care about the
position at which the element to be placed.

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 10
Algorithms
Lab 05 – Working with Advance applications of Arrays, operations on
April 20, 2022 arrays using functions in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


Example 5.9: Program to insert an element in a sorted array.

class Main {
// Inserts a key in arr[] of given capacity. n is current size of arr[].
// This function returns n+1 if insertion is successful, else n.
static int insertSorted(int arr[], int n, int key, int capacity)
{
// Cannot insert more elements if n is already
// more than or equal to capacity
if (n >= capacity)
return n;

int i;
for (i = n - 1; (i >= 0 && arr[i] > key); i--)
arr[i + 1] = arr[i];

arr[i + 1] = key;

return (n + 1);
}

/* Driver program to test above function */


public static void main(String[] args)
{
int arr[] = new int[20];
arr[0] = 12;
arr[1] = 16;
arr[2] = 20;
arr[3] = 40;
arr[4] = 50;
arr[5] = 70;
int capacity = arr.length;
int n = 6;
int key = 26;

System.out.print("\nBefore Insertion: ");


for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");

// Inserting key
n = insertSorted(arr, n, key, capacity);

System.out.print("\nAfter Insertion: ");


for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}}
Output:

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 11
Algorithms
Lab 05 – Working with Advance applications of Arrays, operations on
April 20, 2022 arrays using functions in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


DELETE OPERATION IN SORTED ARRAY
In the delete operation, the element to be deleted is searched using binary search and then delete operation
is performed followed by shifting the elements.

Example 5.10: Program to delete an element from a sorted array

class Main {
// binary search
static int binarySearch(int arr[], int low, int high, int key)
{
if (high < low)
return -1;
int mid = (low + high) / 2;
if (key == arr[mid])
return mid;
if (key > arr[mid])
return binarySearch(arr, (mid + 1), high, key);
return binarySearch(arr, low, (mid - 1), key);
}

/* Function to delete an element */


static int deleteElement(int arr[], int n, int key)
{
// Find position of element to be deleted
int pos = binarySearch(arr, 0, n - 1, key);

if (pos == -1) {
System.out.println("Element not found");
return n;
}

// Deleting element
int i;
for (i = pos; i < n - 1; i++)
arr[i] = arr[i + 1];

return n - 1;
}

/* Driver Code */
public static void main(String[] args)
{

int i;
int arr[] = { 10, 20, 30, 40, 50 };

int n = arr.length;
int key = 30;

System.out.print("Array before deletion:\n");


for (i = 0; i < n; i++)

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 12
Algorithms
Lab 05 – Working with Advance applications of Arrays, operations on
April 20, 2022 arrays using functions in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


System.out.print(arr[i] + " ");

n = deleteElement(arr, n, key);

System.out.print("\n\nArray after deletion:\n");


for (i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}

Output:

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 13
Algorithms
Lab 05 – Working with Advance applications of Arrays, operations on
April 20, 2022 arrays using functions in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


Programming Exercise
1. Suppose A, B, C are arrays of integers. The numbers in array A appear in ascending order while the numbers
in array B appear in descending order. Write a user defined method in Java to produce third array C by
merging arrays A and B in ascending order. Use A, B and C as arguments in the method.
2. Write a menu driven program to do following operation on two dimensional array A of size m x n. You
should use user-defined methods which accept 2-D array A, and its size m and n as arguments. The options are:
a. To input elements into matrix of size m x n
b. To display elements of matrix of size m x n
c. Sum of all elements of matrix of size m x n
d. To display row-wise sum of matrix of size m x n
e. To display column-wise sum of matrix of size m x n
f. To create transpose of matrix of size n x m
3. Write a program to implement Convolution (image, mask) of image processing by performing it on two
dimensional array. Use 4 different kernels to provide the answer.

Convolution: It can be mathematically represented as two ways


g(x,y) = h(x,y) * f(x,y)
It can be explained as the “mask convolved with an image”. Or g(x,y) = f(x,y) * h(x,y)
It can be explained as “image convolved with mask”.
There are two ways to represent this because the convolution operator (*) is commutative. The h(x,y) is the mask or
filter.

What is mask?
Mask is also a signal. It can be represented by a two dimensional matrix. The mask is usually of the order of 1x1,
3x3, 5x5, 7x7. A mask should always be in odd number, because otherwise you cannot find the mid of the mask.
Why do we need to find the mid of the mask? The answer lies below, in topic of, how to perform convolution?

How to perform convolution?


In order to perform convolution on an image, following steps should be taken.

 Flip the mask (horizontally and vertically) only once


 Slide the mask onto the image.
 Multiply the corresponding elements and then add them
 Repeat this procedure until all values of the image has been calculated.

Example of convolution
Let’s perform some convolution. Step 1 is to flip the mask.

Mask
Let’s take our mask to be this.

1 2 3

4 5 6

7 8 9

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 14
Algorithms
Lab 05 – Working with Advance applications of Arrays, operations on
April 20, 2022 arrays using functions in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


Flipping the mask horizontally

3 2 1

6 5 4

9 8 7

Flipping the mask vertically

9 8 7

6 5 4

3 2 1

Image
Let’s consider an image to be like this

2 4 6

8 10 12

14 16 18

Convolution
Convolving mask over image. It is done in this way. Place the center of the mask at each element of an image.
Multiply the corresponding elements and then add them, and paste the result onto the element of the image on which
you place the center of mask.

The box in red color is the mask, and the values in the orange are the values of the mask. The black color box and
values belong to the image. Now for the first pixel of the image, the value will be calculated as
First pixel = (5*2) + (4*4) + (2*8) + (1*10)
= 10 + 16 + 16 + 10 = 52
Place 52 in the original image at the first index and repeat this procedure for each pixel of the image.
Video Tutorial Reference:
 https://www.youtube.com/watch?v=2OW2aLFaV8A
 https://www.youtube.com/watch?v=1GUgD2SBl9A

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 15
Algorithms
Lab 05 – Working with Advance applications of Arrays, operations on
April 20, 2022 arrays using functions in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


4. Write an algorithm first for implementing the Histogram () on numbers that each student will get in each
subject.

Student Name English Urdu Maths Science ICT


Nida 8 7 8 7 9
Hafsa 8 8 5 5 8
Moosa 7 9 9 7 10
Sooraj 7 8 7 6 9

Now for each of the student the marks will be displayed as histogram

Name: Nida
*
* * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
English Urdu Maths Science ICT

5. A University wants you to design a grade book system for their students. The system will generate the result
of course with at least 10 students. Each student will give 3 tests and their average will be recorded.
Furthermore, it will show the lowest marks and highest marks. At the end it will show that overall grade
distribution of the class. For your help the analyst and given you the following output so you can do the
reverse engineering and find how you can use arrays and get the project solved.

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 16
Algorithms

You might also like