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

DSA Module 3 Arrays 4weeks

This document provides an introduction and overview of arrays in Java. It discusses one-dimensional arrays, including how to declare and initialize arrays, access array elements, and specify the array size during program execution. The key learning points are: 1) Arrays allow storing multiple values of the same type in a single variable through indexes. 2) One-dimensional arrays store elements in a linear list. Arrays are declared with syntax like dataType[] arrayName or dataType arrayName[]. 3) Array elements can be accessed using indexes like arrayName[index] which start at 0. 4) The length instance variable returns the size of the array.

Uploaded by

Marnel Mogado
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

DSA Module 3 Arrays 4weeks

This document provides an introduction and overview of arrays in Java. It discusses one-dimensional arrays, including how to declare and initialize arrays, access array elements, and specify the array size during program execution. The key learning points are: 1) Arrays allow storing multiple values of the same type in a single variable through indexes. 2) One-dimensional arrays store elements in a linear list. Arrays are declared with syntax like dataType[] arrayName or dataType arrayName[]. 3) Array elements can be accessed using indexes like arrayName[index] which start at 0. 4) The length instance variable returns the size of the array.

Uploaded by

Marnel Mogado
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Unit 3: ARRAYS

Unit 3
Arrays

Introduction
Before we formally define an array, let’s consider the following problems. We want
to write a Java program that reads five numbers, finds their sum, and prints the numbers in
reverse order.
In your previous programing subjects, you learned how to read numbers, print them,
and find their sum. What’s different here is that we want to print the numbers in reverse
order. We cannot print the first four numbers until we have printed the fifth, and so on. This
means that we need to store all the numbers before we can print them in reverse order.

Unit Learning Outcomes


At the end of the unit, you will be able to:
a. differentiate and understand the values of the different types of arrays
b. discover how to manipulate data in a one-multi-dimensional and two-dimensional
array
c. learn how to search and sort an array

Topic 1: One Dimensional Array


Time Allotment: 4 hours

Learning Objectives
At the end of the session, you will be able to:
a. declare and create arrays
b. initialize arrays
c. index array elements correctly
d. access array values
e. sort array elements in ascending and descending order
f. search for specific element in an array

1
Unit 3: ARRAYS

Activating Prior Knowledge


What comes to your mind when you hear the word ARRAY? Write your answer on the empty
boxes provided below.

Presentation of Contents

An array is a collection (sequence) of a fixed number of variables called elements or


components, wherein all the elements are of the same data type. There are 3 types of an array
namely one-dimensional array, two-dimensional array and multi-dimensional array.

One-Dimensional Array
A one-dimensional array is an array in which the elements are arranged in a list form.

Declaring a One-Dimensional Array


The general form to declare a one-dimensional array is:

dataType[] arrayName; //Line 1

where dataType is the element type.

Because an array is an object, arrayName is a reference variable. Therefore, the


preceding statement only declares a reference variable. Before we can store the data, we must
instantiate the array object.

The general syntax to instantiate an array object is:

arrayName = new dataType[intExp]; //Line 2

2
Unit 3: ARRAYS
where intExp is any expression that evaluates to a positive integer. Also, the value of
intExp specifies the number of elements in the array.
When an array is instantiated, Java automatically initializes its elements to their
default values. For example, the elements of numeric arrays are initialized to 0, the elements
of char arrays are initialized to the null character, which is '\u0000', the elements of boolean
arrays are initialized to false.

You can combine the statements in Lines 1 and 2 into one statement as follows:

dataType[] arrayName = new dataType[intExp]; //Line 3

The statement:

int[] num = new int[5];

declares and creates the array num consisting of 5 elements. Each element is of type
int. The elements are accessed as num[0], num[1], num[2], num[3], and num[4]. Below
illustrates the array num.
0
0
0
0

Alternate Ways to Declare a One-Dimensional Array


Java allows you to declare arrays as follows:

int list[]; //Line 1

Here, the operator [] appears after the identifier list, not after the data type int. You
should be careful when declaring arrays as in Line 1. Consider the following statements:

int alpha[], beta; //Line 2


int[] gamma, delta; //Line 3

The statement in Line 2 declares the variables alpha and beta. Similarly, the statement
in Line 3 declares the variables gamma and delta. However, the statement in Line 2 declares
only alpha to be an array reference variable, while the variable beta is an int variable. On the
other hand, the statement in Line 3 declares both gamma and delta to be array reference
variables.

Traditionally, Java programmers declare arrays as shown in Line 3. We recommend


that you do the same.

3
Unit 3: ARRAYS

Accessing Array Elements

The general form (syntax) used to access an array element is:

arrayName[indexExp]

where indexExp, called the index, is an expression whose value is a nonnegative


integer less than the size of the array. The index value specifies the position of the element in
the array. In Java, the array index starts at 0. In Java, [] is an operator called the array
subscripting operator.

Consider the following statement:

int[] list = new int[10];

This statement declares an array list of 10 elements. The elements are list[0], list[1], . .
., list[9]. In other words, we have declared 10 variables of type int as shown below.

The assignment statement:

list[5] = 34;

stores 34 into list[5], which is the sixth element of the array list as shown below.

Suppose i is an int variable. Then, the assignment statement:

list[3] = 63;
is equivalent to the assignment statements:

i = 3;
list[i] = 63;

If i is 4, then the assignment statement:

list[2 * i - 3] = 58;

stores 58 into list[5], because 2 * i - 3 evaluates to 5. The index expression is


evaluated first, giving the position of the element in the array.

Next, consider the following statements:

4
Unit 3: ARRAYS
list[3] = 10;
list[6] = 35;
list[5] = list[3] + list[6];
The first statement stores 10 into list[3], the second statement stores 35 into list[6],
and the third statement adds the contents of list[3] and list[6] and stores the result into list[5].

Specifying Array Size during Program Execution


When you include a statement in a program to instantiate an array object, it is not
necessary to know the size of the array at compile time. During program execution, you can
first prompt the user to specify the size of the array and then instantiate the object.

The following statements illustrate this concept (suppose that console is a Scanner
object initialized to the standard input device):

int arraySize; //Line 1

System.out.print("Enter the size of the array: "); //Line 2


arraySize = console.nextInt(); //Line 3
System.out.println(); //Line 4

int[] list = new int[arraySize]; //Line 5

The statement in Line 2 asks the user to enter the size of the array when the program
executes. The statement in Line 3 inputs the size of the array into arraySize. During program
execution, the system uses the value of the variable arraySize to instantiate the object list. For
example, if the value of arraySize is 15, list is an array of size 15.

Array Initialization during Declaration


Like any other primitive data type variable, an array can also be initialized with
specific values when it is declared. For example, the following Java statement declares an
array, sales, of five elements and initializes those elements to specific values:

double[] sales = {12.25, 32.50, 16.90, 23, 45.68};

The initializer list contains values, called initial values, that are placed between
braces and separated by commas. Here, sales[0] = 12.25, sales[1] = 32.50, sales[2] = 16.90,
sales[3] = 23.00, and sales[4]= 45.68.

Note the following about declaring and initializing arrays:


 When declaring and initializing arrays, the size of the array is determined by the
number of initial values in the initializer list within the braces.
 If an array is declared and initialized simultaneously, we do not use the
operator new to instantiate the array object.

Arrays and the Instance Variable length

5
Unit 3: ARRAYS
Recall that an array is an object; therefore, to store data, the array object must be
instantiated. Associated with each array that has been instantiated (that is, for which memory
has been allocated to store data), there is a public (final) instance variable length. The
variable length contains the size of the array. Because length is a public member, it can be
directly accessed in a program using the array name and the dot operator.

Consider the following declaration:


int[] list = {10, 20, 30, 40, 50, 60};

This statement creates the array list of six elements and initializes the elements using
the values given. Here, list.length is 6.

Consider the following statement:

int[] numList = new int[10];

This statement creates the array numList of 10 elements and initializes each element
to 0. Because the number of elements of numList is 10, the value of numList.length is 10.

Now consider the following statements:


numList[0] = 5;
numList[1] = 10;
numList[2] = 15;
numList[3] = 20;

These statements store 5, 10, 15, and 20, respectively, in the first four elements of
numList. Even though we put data into only the first four elements, the value of
numList.length is 10, the total number of array elements.

Note: Once an array is instantiated, its size remains fixed. In other words, if you have
instantiated an array of 5 elements, the number of elements of the array remains 5. If you
need to increase the size of the array, then you must instantiate another array of the desired
size and copy the data stored in the first array into the new array. In the next section, we show
how to copy the elements of one array into another array.

Processing One-Dimensional Arrays

Some basic operations performed on a one-dimensional array are initializing the


array, reading data into the array, storing output data in the array, and finding the largest and/
or smallest element in the array. If the data type of an array element is numeric, some
common operations are to find the sum and average of the elements of the array. Each of
these operations requires the ability to step through the elements of the array, which is easily
accomplished by using a loop. Suppose that we have the following statements:

int[] list = new int[100]; //list is an array of size 100

The following for loop steps through each element of the array list, starting at the first
element of list:

for (int i = 0; i < list.length; i++) //Line 1

6
Unit 3: ARRAYS
//process list[i], the (i + 1)th element of list //Line 2

If processing list requires inputting data into list, the statement in Line 2 takes the
form of an input statement, such as in the following code. The following statements read 100
numbers from the keyboard and store the numbers into list:

for (int i = 0; i < list.length; i++) //Line 1


list[i] = console.nextInt(); //Line 2

Similarly, if processing list requires outputting data, then the statement in Line 2 takes
the form of an output statement. The following for loop outputs the elements of list:

for (int i = 0; i < list.length; i++) //Line 1


System.out.print(list[i] + " "); //Line 2

The following example shows how loops are used to process arrays. The following
declaration is used throughout this example:

double[] sales = new double[10];


double largestSale, sum, average;

The first statement creates the array sales of 10 elements, with each element of type
double. The meaning of the other statements is clear. Also, notice that the value of
sales.length is 10.

Loops can be used to process arrays in several ways:

1. Initializing an array to a specific value: Suppose that you want to initialize every
element of the array sales to 10.00. You can use the following loop:

for (int index = 0; index < sales.length; index++)


sales[index] = 10.00;

2. Reading data into an array: The following loop inputs data into the array sales. For
simplicity, we assume that the data is entered at the keyboard one number per line.

for (int index = 0; index < sales.length; index++)


sales[index] = console.nextDouble();

3. Printing an array: The following loop outputs the elements of array sales. For
simplicity, we assume that the output goes to the screen.

for (int index = 0; index < sales.length; index++)


System.out.print(sales[index] + " ");

4. Finding the sum and average of an array: Because the array sales, as its name implies,
represents certain sales data, it may be desirable to find the total sale and average sale
amounts. The following Java code finds the sum of the elements of the array sales
(total sales) and the average sale amount:

7
Unit 3: ARRAYS

sum = 0;
for (int index = 0; index < sales.length; index++)
sum = sum + sales[index];

if (sales.length != 0)
average = sum / sales.length;
else
average = 0.0;

Using For Loop – One Dimensional Array

class OnedimensionalLoop
{
public static void main(String args[])
{
int[ ] a={10,20,30,40,50};//declaration and initialization
System.out.println("One dimensional array elements are :\n");
for(int i=0;i<a.length;i++)
{
System.out.println("a["+i+"]:"+a[i]);
}
}
}

Output:
One dimensional array elements are :
a[0]:10
a[1]:20
a[2]:30
a[3]:40
a[4]:50

Using String
1. We declared one-dimensional string array with the elements strings.
2. To print strings from the string array. for i=0 to i<length of the string print string which is
at the index str[i].

class OneDimensionString

8
Unit 3: ARRAYS
{
public static void main(String[] args)
{
//declare and initialize one dimension array
String[] str = new String[]{"one", "two", "three", "four"};
System.out.println("These are elements of one Dimensional array.");
for (int i = 0; i < str.length; i++)
{
System.err.println(str[i] + " ");
}
}
}

Output:
These are elements of one Dimensional array.
one
two
three
four

Algorithm
- An algorithm is an effective method for solving a problem using a finite sequence of
instructions. Algorithms are used for calculation, data processing, and many other fields.
- An algorithm is a finite set of well-defined instructions for accomplishing some tasks which,
given an initial state, will result in a corresponding recognizable end-state.

Classifications of Algorithms
1. Linear Search Algorithm
- Linear search or sequential search is a method for finding a particular value in a list, that
consists in checking every one of its elements, one at a time and in sequence, until the desired
one is found.
- The simplest way to find an object in an array is to start at the beginning and inspect each
element, one after the other, until the object is found.

2. Bubble Sort Algorithm


- Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to
be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong
order. The pass through the list is repeated until no swaps are needed, which indicates that the
list is sorted.

3. Binary Search Algorithm


- A binary search algorithm is an algorithm for locating the position of an element in a sorted
list. It inspects the middle element of the sorted list: if equal to the sought value, then the
position has been found; otherwise, the upper half or lower half is chosen for further
searching based on whether the sought value is greater than or less than the middle element.
The method reduces the number of elements needed to be checked by a factor of two each
time, and finds the sought value if it exists in the list.
- The binary search uses the “divide and conquer” strategy. It repeatedly divides the array into
two pieces and then searches the piece that could contain the target value.

9
Unit 3: ARRAYS

Linear Search in Java


Linear search is used to search a key element from multiple elements. Linear search is less used today
because it is slower than binary search and hashing.

Algorithm:

o Step 1: Traverse the array


o Step 2: Match the key element with array element
o Step 3: If key element is found, return the index position of the array element
o Step 4: If key element is not found, return -1

Let's see an example of linear search in java where we are going to search an element sequentially
from an array.

public class LinearSearchExample{


public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){
if(arr[i] == key){
return i;
}
}
return -1;
}
public static void main(String a[]){
int[] a1= {10,20,30,50,70,90};
int key = 50;
System.out.println(key+" is found at index: "+linearSearch(a1, key));
}
}

Output:
50 is found at index: 3

Linear Search in Java (Another way)


You can also use a method where array is not predefined. Here, user has to put the elements as input
and select one element to check its location.

import java.util.Scanner;

class LinearSearchExample2
{
public static void main(String args[])
{

10
Unit 3: ARRAYS
int c, n, search, array[];

Scanner in = new Scanner(System.in);


System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];

System.out.println("Enter those " + n + " elements");

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


array[c] = in.nextInt();

System.out.println("Enter value to find");


search = in.nextInt();

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


{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) /* Element to search isn't present */
System.out.println(search + " isn't present in array.");
}
}

Java program to sort a one dimensional array in ascending order


Here, we are implementing a java program to sort an array (one-dimensional array) in ascending
order? We are reading array elements, arranging them in ascending order and printing the sorted
array.
Given an array and we have to sort its elements in ascending order and print the sorted array using
java program.

Example:
Input:
Array (elements will be read in program): 25 54 36 12 48 88 78 95 54 55
Output:
Sorted List in Ascending Order :
12 25 36 48 54 54 55 78 88 95

Program to sort an array in ascending order in java


import java.util.Scanner;

11
Unit 3: ARRAYS
public class ExArraySort
{
public static void main(String args[])
{
// initialize the objects.
int n, i, j, temp;
int[ ] arr = new int[50];
Scanner scan = new Scanner(System.in);

// enter number of elements to enter.


System.out.print("Enter number for the array elements : ");
n = scan.nextInt();

// enter elements.
System.out.println("Enter " +n+ " Numbers : ");
for(i=0; i<n; i++)
{
arr[i] = scan.nextInt();
}

// sorting array elements.


System.out.print("Sorting array : \n");
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

System.out.print("Array Sorted Successfully..!!\n");

// array in ascending order.


System.out.print("Sorted List in Ascending Order : \n");
for(i=0; i<n; i++)
{
System.out.print(arr[i]+ " ");
}
}
}

Output

Enter number for the array elements : 10


Enter 10 Numbers :
25
54
36
12
48

12
Unit 3: ARRAYS
88
78
95
54
55
Sorting array :
Array Sorted Successfully..!!
Sorted List in Ascending Order :
12 25 36 48 54 54 55 78 88 95

Java Program to Sort the Array in Descending Order


This is a Java Program to Sort the Array in Descending Order.
Enter size of array and then enter all the elements of that array. Now with the help of for loop and
temp variable we sort the array in descending order.
Here is the source code of the Java Program to Sort the Array in Descending Order. The Java program
is successfully compiled and run on a Windows system. The program output is also shown below.

import java.util.Scanner;
public class Descending_Order
{
public static void main(String[] args)
{
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int[ ] a = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] < a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("Descending Order:");
for (int i = 0; i < n - 1; i++)

13
Unit 3: ARRAYS
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}
Output:
Enter no. of elements you want in array:5
Enter all the elements:
2
3
5
1
4
Descending Order:5,4,3,2,1

Binary Search Algorithm

Binary search is a divide and conquer algorithm. Like all divide and conquer algorithms,
Binary Search first divides a large array into smaller sub-arrays and then
operate the sub-arrays. But instead of operating on both sub-arrays, it discards one
sub-array and continue on the second sub-array. This decision of discarding one
sub-array is made in just one comparison.
So Binary Search basically reduces the search space to half at each step.
By search space we mean sub-array of given array where the target value is located (if present in the
array). Initially, the search space is the entire array and binary
search redefine the search space at every step of the algorithm by using the
property of the array that is sorted. It does so by comparing the mid value in the
search space to the target value. If the target value matches the middle element, its position in the
array is returned else it discards half of the search space based on the comparison result.
Let us track the search space by using two index –start and end. Initially
start = 0, and end = n-1. At each step, we find the mid value in the search space
and compares it with target value. There three cases possible

Case 1: if target = A[mid], we return mid.


Case 2: if target < A[mid], we discard all elements in the right search space
including the mid element i.e. A[mid….high]. now our
new high would be mid-1.
Case 3: if target > A[mid], we discard all elements in the left search space including the mid element
i.e. A[low…mid]. Now our new low would be mid+1.
We repeat the process until target is found or our search space is exhausted. Let’s understand
this by taking an example.
Let arr = {2, 3, ,5 ,7 ,8, 10, 12, 15, 18,
20}
target = 7

14
Unit 3: ARRAYS

Binary Search Algorithm


public class BinarySearch
{
// find out if a key x exists in the sorted array A
// or not using binary search algorithm
public static int binarySearch(int[] A, int x)
{
// search space is A[left..right]
int left = 0, right = A.length - 1;

// till search space consists of at-least one element


while (left <= right)

15
Unit 3: ARRAYS
{
// we find the mid value in the search space and
// compares it with key value

int mid = (left + right) / 2;

// key value is found


if (x == A[mid]) {
return mid;
}

// discard all elements in the right search space


// including the mid element
else if (x < A[mid]) {
right = mid - 1;
}

// discard all elements in the left search space


// including the mid element
else {
left = mid + 1;
}
}

// x doesn't exist in the array


return -1;
}

public static void main(String[] args)


{
int[] A = { 2, 5, 6, 8, 9, 10 };
int key = 5;

int index = binarySearch(A, key);

if (index != -1) {
System.out.println("Element found at index " + index);
} else {
System.out.println("Element not found in the array");
}
}
}

Application
1. Write Java statements that does the following:
a. Declare an array alpha of 15 elements of type int.

____________________________________________________________

16
Unit 3: ARRAYS
b. Output the value of the tenth element of the array alpha.

____________________________________________________________
c. Set the value of the fifth element of the array alpha to 35.

____________________________________________________________
d. Set the value of the ninth element of the array alpha to the sum of the
sixth and thirteenth elements of the array alpha.

____________________________________________________________
e. Set the value of the fourth element of the array alpha to three times
the value of the eighth element, minus 57.

___________________________________________________________

2. Write a program that accepts 10 integer inputs from a user and store them in an array.
The program must again ask the user to give another number and tell the user whether
that number is present or not in the array. If the number is present, the program must
identify its array location otherwise it should display a message “Number not
Found!”.

17
Unit 3: ARRAYS

Feedback
1. Analyze each statement carefully. Mark the following statements as true or false. Write
your answer on the space provided for each item.
__________ a. A double type is an example of a primitive data type.
__________ b. A one-dimensional array is an example of a structured data type.
__________ c. Arrays can be passed as parameters to a method.
__________ d. A method can return a value of the type array.
__________ e. The size of an array is determined at compile time.
___________ f. Given the declaration:
int[] list = new int[10];
the statement:
list[5] = list[3] + list[2];
updates the content of the fifth element of the array list.
__________ g. If an array index goes out of bounds, the program terminates in an error.

2. What is the output of the following program?


public class Exercise
{
public static void main(String[] args)
{
int[] one = new int[5];
int[] two = new int[10];
for (int j = 0; j < 5; j++)
one[j] = 5 * j + 3;
System.out.print("One contains: ");
for (int j = 0; j < 5; j++)

18
Unit 3: ARRAYS
System.out.print(one[j] + " ");
System.out.println();
for (int j = 0; j < 5; j++)
{
two[j] = 2 * one[j] - 1;
two[j + 5] = one[4 - j] + two[j];
}
System.out.print("Two contains: ");
for (int j = 0; j < 10; j++)
System.out.print(two[j] + " ");
System.out.println();
}
}

Output:

3. Identify the following. Write your answer


on the space provided before each item.
______________________ a. A sequence of objects all of which have the same type.
______________________ b. It divides a large array into smaller sub-arrays and then
operate the sub-arrays. But instead of operating on both
sub-arrays, it discards one sub-array and continue on
the second sub-array.
______________________ c. It is how the elements of an array are numbered
consecutively.
______________________ d. It works by repeatedly stepping through the list to be
sorted, comparing each pair of adjacent items and
swapping them if they are in the wrong order.
______________________ e. It is an effective method for solving a problem using a
finite sequence of instructions. Algorithms are used for
calculation, data processing, and many other fields.
______________________ f. It is how each object is called in an array.
______________________ g. It is a method for finding a particular value in a list that
consists in checking every one of its elements, one at a
time and in sequence, until the desired one is found.

Topic 2: Multi-Dimensional Arrays


Time Allotment: 4 hours

Learning Objectives
At the end of the session, you will be able to:
a. declare and create two- and multi-dimensional arrays

19
Unit 3: ARRAYS
b. initialize and access multi-dimensional array values
c. sort multi-dimensional array elements in ascending and descending order
d. search for specific element in a multi-dimensional array

Activating Prior Knowledge


What comes to your mind when you hear the word ARRAY? Write your answer on
the empty boxes provided below.

Presentation of Contents

Multidimensional Arrays can be defined in simple words as array of arrays. Data in


multidimensional arrays are stored in tabular form (in row major order).
Syntax:
data_type[1st dimension][2nd dimension][]..[Nth
dimension] array_name = new data_type[size1][size2]….[sizeN];
where:
 data_type: Type of data to be stored in the array. For example: int, char, etc.
 dimension: The dimension of the array created.
For example: 1D, 2D, etc.
 array_name: Name of the array
 size1, size2, …, sizeN: Sizes of the dimensions respectively.

Examples:

Two dimensional array:


int[][] twoD_arr = new int[10][20];

Three dimensional array:


int[][][] threeD_arr = new int[10][20][30];

20
Unit 3: ARRAYS
Size of multidimensional arrays: The total number of elements that can be stored in a
multidimensional array can be calculated by multiplying the size of all the dimensions.
For example:
The array int[][] x = new int[10][20] can store a total of (10*20) = 200 elements.
Similarly, array int[][][] x = new int[5][10][20] can store a total of (5*10*20) = 1000
elements.

Two – dimensional Array (2D-Array)


Two – dimensional array is the simplest form of a multidimensional array. A two –
dimensional array can be seen as an array of one – dimensional array for easier
understanding.
Indirect Method of Declaration:
Declaration – Syntax:
data_type[][] array_name = new data_type[x][y];
For example: int[][] arr = new int[10][20];
Initialization – Syntax:
array_name[row_index][column_index] = value;
For example: arr[0][0] = 1;
Example:
class GFG {
public static void main(String[] args)
{

int[][] arr = new int[10][20];


arr[0][0] = 1;

System.out.println("arr[0][0] = " + arr[0][0]);


}
}

Output:
arr[0][0] = 1
Direct Method of Declaration:
Syntax:
data_type[][] array_name = {
{valueR1C1, valueR1C2, ....},
{valueR2C1, valueR2C2, ....}
};
For example: int[][] arr = {{1, 2}, {3, 4}};

Example:
class GFG {
public static void main(String[] args)
{

int[][] arr = { { 1, 2 }, { 3, 4 } };

for (int i = 0; i < 2; i++)

21
Unit 3: ARRAYS
for (int j = 0; j < 2; j++)
System.out.println("arr[" + i + "][" + j + "] = "
+ arr[i][j]);
}
}

Output:
arr[0][0] = 1
arr[0][1] = 2
arr[1][0] = 3
arr[1][1] = 4

Accessing Elements of Two-Dimensional Arrays


Elements in two-dimensional arrays are commonly referred by x[i][j] where ‘i’ is the row
number and ‘j’ is the column number.
Syntax:
x[row_index][column_index]

For example:
int[][] arr = new int[10][20];
arr[0][0] = 1;

The above example represents the element present in first row and first column.
Note: In arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for row_index
2, actual row number is 2+1 = 3.

Example:
class GFG {
public static void main(String[] args)
{
int[][] arr = { { 1, 2 }, { 3, 4 } };

System.out.println("arr[0][0] = " + arr[0][0]);


}
}

Output:
arr[0][0] = 1

Representation of 2D array in Tabular Format: A two – dimensional array can be seen as


a table with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to (x-1) and
column number ranges from 0 to (y-1). A two – dimensional array ‘x’ with 3 rows and 3
columns is shown below:

22
Unit 3: ARRAYS

Print 2D array in tabular format:


To output all the elements of a Two-Dimensional array, use nested for loops. For this two for
loops are required, One to traverse the rows and another to traverse columns.

Example:
class GFG {
public static void main(String[] args)
{
int[][] arr = { { 1, 2 }, { 3, 4 } };

for (int i = 0; i < 2; i++) {


for (int j = 0; j < 2; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}

Output:
12
34

Three – dimensional Array (3D-Array)


Three – dimensional array is a complex form of a multidimensional array. A three –
dimensional array can be seen as an array of two – dimensional array for easier
understanding.

Indirect Method of Declaration:


Declaration – Syntax:
data_type[][][] array_name = new data_type[x][y][z];
For example: int[][][] arr = new int[10][20][30];

Initialization – Syntax:
array_name[array_index][row_index][column_index] = value;
For example: arr[0][0][0] = 1;

Example:
class GFG {
public static void main(String[] args)
{
int[][][] arr = new int[10][20][30];
arr[0][0][0] = 1;

23
Unit 3: ARRAYS

System.out.println("arr[0][0][0] = " + arr[0][0][0]);


}
}

Output:
arr[0][0][0] = 1

Direct Method of Declaration:


Syntax:
data_type[][][] array_name = {
{
{valueA1R1C1, valueA1R1C2, ....},
{valueA1R2C1, valueA1R2C2, ....}
},
{
{valueA2R1C1, valueA2R1C2, ....},
{valueA2R2C1, valueA2R2C2, ....}
}
};

For example: int[][][] arr = { {{1, 2}, {3, 4}}, {{5, 6}, {7, 8}} };

Example:
class GFG {
public static void main(String[] args)
{
int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };

for (int i = 0; i < 2; i++)


for (int j = 0; j < 2; j++)
for (int z = 0; z < 2; z++)
System.out.println("arr[" + i + "][" + j + "][" + z + "] = "
+ arr[i][j][z]);
}
}

Output:
arr[0][0][0] = 1
arr[0][0][1] = 2
arr[0][1][0] = 3
arr[0][1][1] = 4
arr[1][0][0] = 5
arr[1][0][1] = 6
arr[1][1][0] = 7
arr[1][1][1] = 8

Accessing Elements of Three-Dimensional Arrays


Elements in three-dimensional arrays are commonly referred by x[i][j][k] where ‘i’ is the
array number, ‘j’ is the row number and ‘k’ is the column number.

24
Unit 3: ARRAYS

Syntax:
x[array_index][row_index][column_index]
For example:
int[][][] arr = new int[10][20][30];
arr[0][0][0] = 1;

The above example represents the element present in the first row and first column of the first
array in the declared 3D array.
Note: In arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for row_index
2, actual row number is 2+1 = 3.

Example:
class GFG {
public static void main(String[] args)
{
int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };

System.out.println("arr[0][0][0] = " + arr[0][0][0]);


}
}

Output:
arr[0][0][0] = 1

Representation of 3D array in Tabular Format: A three – dimensional array can be seen


as a tables of arrays with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to
(x-1) and column number ranges from 0 to (y-1). A three – dimensional array with 3 array
containing 3 rows and 3 columns is shown below:

25
Unit 3: ARRAYS
Print 3D array in tabular format:
To output all the elements of a Three-Dimensional array, use nested for loops. For this three
for loops are required, One to traverse the arrays, second to traverse the rows and another to
traverse columns.
Example:
class GFG {
public static void main(String[] args)
{
int[][][] arr = { { { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } } };

for (int i = 0; i < 2; i++) {

for (int j = 0; j < 2; j++) {

for (int k = 0; k < 2; k++) {

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


}

System.out.println();
}
System.out.println();
}
}
}

class GFG {
public static void main(String[] args)
{
int[][][] arr = { { { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } } };

for (int i = 0; i < 2; i++) {


for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
System.out.print(arr[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}
}
}

Output:
12
34

26
Unit 3: ARRAYS

56
78

Inserting a Multi-dimensional Array during Runtime:


This topic is forced n taking user-defined input into a multidimensional array during runtime.
It is focused on the user first giving all the input to the program during runtime and after all
entered input, the program will give output with respect to each input accordingly. It is useful
when the user wishes to make input for multiple Test-Cases with multiple different values
first and after all those things done, program will start providing output.
As an example, let’s find the total number of even and odd numbers in an input array. Here,
we will use the concept of a 2-dimensional array. Here are a few points that explain the use of
the various elements in the upcoming code:
 Row integer number is considered as the number of Test-Cases and Column values are
considered as values in each Test-Case.
 One for() loop is used for updating Test-Case number and another for() loop is used for
taking respective array values.
 As all input entry is done, again two for() loops are used in the same manner to execute
the program according to the condition specified.
 The first line of input is the total number of TestCases.
 The second line shows the total number of first array values.
 The third line gives array values and so on.

Implementation:
import java.util.Scanner;

public class GFGTestCase {


public static void main(
String[] args)
{
// Scanner class to take
// values from console
Scanner scanner = new Scanner(System.in);

// totalTestCases = total
// number of TestCases
// eachTestCaseValues =
// values in each TestCase as
// an Array values
int totalTestCases, eachTestCaseValues;

// takes total number of


// TestCases as integer number
totalTestCases = scanner.nextInt();

// An array is formed as row


// values for total testCases
int[][] arrayMain = new int[totalTestCases][];

27
Unit 3: ARRAYS
// for loop to take input of
// values in each TestCase
for (int i = 0; i < arrayMain.length; i++) {
eachTestCaseValues = scanner.nextInt();
arrayMain[i] = new int[eachTestCaseValues];
for (int j = 0; j < arrayMain[i].length; j++) {
arrayMain[i][j] = scanner.nextInt();
}
} // All input entry is done.

// Start executing output


// according to condition provided
for (int i = 0; i < arrayMain.length; i++) {

// Initialize total number of


// even & odd numbers to zero
int nEvenNumbers = 0, nOddNumbers = 0;

// prints TestCase number with


// total number of its arguments
System.out.println(
"TestCase " + i + " with "
+ arrayMain[i].length + " values:");
for (int j = 0; j < arrayMain[i].length; j++) {
System.out.print(arrayMain[i][j] + " ");

// even & odd counter updated as


// eligible number is found
if (arrayMain[i][j] % 2 == 0) {
nEvenNumbers++;
}
else {
nOddNumbers++;
}
}
System.out.println();

// Prints total numbers of


// even & odd
System.out.println(
"Total Even numbers: " + nEvenNumbers
+ ", Total Odd numbers: " + nOddNumbers);
}
}
}

Input:
2
2
12

28
Unit 3: ARRAYS
3
123

Output:
TestCase 0 with 2 values:
12
Total Even numbers: 1, Total Odd numbers: 1
TestCase 1 with 3 values:
123
Total Even numbers: 1, Total Odd numbers: 2

Input:
3
8
1 2 3 4 5 11 55 66
5
100 101 55 35 108
6
3 80 11 2 1 5

Output:
TestCase 0 with 8 values:
1 2 3 4 5 11 55 66
Total Even numbers: 3, Total Odd numbers: 5
TestCase 1 with 5 values:
100 101 55 35 108
Total Even numbers: 2, Total Odd numbers: 3
TestCase 2 with 6 values:
3 80 11 2 1 5
Total Even numbers: 2, Total Odd numbers: 4

29
Unit 3: ARRAYS
Sort the two dimensional (2D) array – In-place

Problem: Given a two-dimensional array where each individual row is sorted in ascending
order. Your task to sort the entire 2d array in ascending order. Write an algorithm for the
sorting.

Example:
Given Array:
[[5, 12, 17, 21, 23]
[1, 2, 4, 6, 8]
[12, 14, 18, 19, 27]
[3, 7, 9, 15, 25]]

Sorted Array:
[[1, 2, 3, 4, 5]
[6, 7, 8, 9, 12]
[12, 14, 15, 17, 18]
[19, 21, 23, 25, 27]]

Approach:
 Each row is sorted, we will take advantage of this.
 Since each row is sorted which means the first column for each row will have the
minimum element among their respective rows, which also means that minimum
element in the entire matrix will be from the first column. So we will pick that smallest
element and replace it with the first element in the matrix.
 Now we have successfully placed the right element at the first position in the array. Now
we will restore the original property of the array which is each row is sorted. So we will
shift the swapped element (earlier with the first position of the matrix) till it finds its
right place in the array.
 Now we need to find the second most minimum element for the second position which
will be among elements at the second column in the first row and first column in the rest
of the rows. Once found, swap it and again reorder to restore the original property.
 Repeat this process until the entire array is sorted.

30
Unit 3: ARRAYS
See the example below for more understanding

31
Unit 3: ARRAYS
Complete Code:
public class
Sort2DArray
{
public void sort(int [][] input){
System.out.println("Given Array: ");
print(input);
for (int row = 0; row <input.length-1 ; row++) {
for (int col = 0; col <input[row].length ; col++) {
placeCurrentElementAtCorrectPosition(input, row, col, row+1);
}
}
System.out.println("Sorted Array: ");
print(input);
}

void placeCurrentElementAtCorrectPosition(int [][] input, int curr_row, int curr_col,


int rowIndex){
int min = input[curr_row][curr_col];
int min_row = curr_row;
for (int i = rowIndex; i <input.length ; i++) {
if(min>input[i][0]){
min = input[i][0];
min_row = i;
}
}

//swap if needed
if(curr_row!=min_row){
int num = input[curr_row][curr_col];
input[curr_row][curr_col] = input[min_row][0];
input[min_row][0] = num;

//reorder the swapped row


reorder(input, min_row);
}
}

void reorder(int [][] input, int row){


for (int col = 0; col <input[row].length-1 ; col++) {
if(input[row][col]>input[row][col+1]) {
//swap
int num = input[row][col];
input[row][col] = input[row][col+1];
input[row][col+1] = num;
}else{

32
Unit 3: ARRAYS
//row is sorted, no need to check further
break;
}
}
}

void print(int [][] input){


for (int row = 0; row <input.length ; row++) {
for (int col = 0; col < input[row].length; col++) {
int currNum = input[row][col];
System.out.print(currNum + " ");
}
System.out.println();
}
}

public static void main(String[] args) {


int [][] input = { { 5, 12, 17, 21, 23},
{ 1, 2, 4, 6, 8},
{12, 14, 18, 19, 27},
{ 3, 7, 9, 15, 25}
};

Sort2DArray s = new Sort2DArray();


s.sort(input);
}
}

Output:
Given Array:
5 12 17 21 23
1 2 4 6 8
12 14 18 19 27
3 7 9 15 25

Sorted Array:
1 2 3 4 5
6 7 8 9 12
12 14 15 17 18
19 21 23 25 27

33
Unit 3: ARRAYS
Search element in a sorted matrix
Given a sorted matrix mat[n][m] and an element ‘x’. Find position of x in the matrix if it is
present, else print -1. Matrix is sorted in a way such that all elements in a row are sorted in
increasing order and for row ‘i’, where 1 <= i <= n-1, first element of row 'i' is greater than or
equal to the last element of row 'i-1'. The approach should have O(log n + log m) time
complexity. Examples:

Input : mat[][] = { {1, 5, 9},


{14, 20, 21},
{30, 34, 43} }
x = 14
Output : Found at (1, 0)

Input : mat[][] = { {1, 5, 9, 11},


{14, 20, 21, 26},
{30, 34, 43, 50} }
x = 42
Output : -1

A Simple Solution is to one by one compare x with every element of matrix. If matches, then
return position. If we reach end, return -1. Time complexity of this solution is O(n x m).
An efficient solution is to typecast given 2D array to 1D array, then apply binary search on
the typecasted array.

Another efficient approach that doesn’t require typecasting is explained below.

1) Perform binary search on the middle column till only two elements are left or till the
middle element of some row in the search is the required element 'x'. This search is done
to skip the rows that are not required
2) The two left elements must be adjacent. Consider the rows of two elements and do
following
a) check whether the element 'x' equals to the middle element of any one of the 2 rows
b) otherwise according to the value of the element 'x' check whether it is present in the 1st
half of 1st row, 2nd half of 1st row,1st half of 2nd row or 2nd half of 2nd row.

Note: This approach works for the matrix n x m where 2 <= n. The algorithm can be modified
for matrix 1 x m, we just need to check whether 2nd row exists or not

Example:
Consider: | 1 2 3 4|
x = 3, mat = | 5 6 7 8| Middle column:
| 9 10 11 12| = {2, 6, 10, 14}
|13 14 15 16| perform binary search on them since, x < 6, discard the last 2
rows as 'a' will not lie in them (sorted matrix)

Now, only two rows are left

34
Unit 3: ARRAYS
| 1 2 3 4|
x = 3, mat = | 5 6 7 8| Check whether element is present on the middle elements of these
rows = {2, 6} x != 2 or 6

If not, consider the four sub-parts


1st half of 1st row = {1}, 2nd half of 1st row = {3, 4}
1st half of 2nd row = {5}, 2nd half of 2nd row = {7, 8}

According the value of 'x' it will be searched in the


2nd half of 1st row = {3, 4} and found at (i, j): (0, 2)

// java implementation to search


// an element in a sorted matrix
import java.io.*;

class GFG
{
static int MAX = 100;

// This function does Binary search for x in i-th


// row. It does the search from mat[i][j_low] to
// mat[i][j_high]
static void binarySearch(int mat[][], int i, int j_low, int j_high, int x)
{
while (j_low <= j_high)
{
int j_mid = (j_low + j_high) / 2;

// Element found
if (mat[i][j_mid] == x)
{
System.out.println ( "Found at (" + i + ", " + j_mid +")");
return;
}

else if (mat[i][j_mid] > x)


j_high = j_mid - 1;

else
j_low = j_mid + 1;
}

// element not found


System.out.println ( "Element no found");
}

35
Unit 3: ARRAYS
// Function to perform binary search on the mid
// values of row to get the desired pair of rows
// where the element can be found
static void sortedMatrixSearch(int mat[][], int n, int m, int x)
{
// Single row matrix
if (n == 1)
{
binarySearch(mat, 0, 0, m - 1, x);
return;
}

// Do binary search in middle column.


// Condition to terminate the loop when the
// 2 desired rows are found
int i_low = 0;
int i_high = n - 1;
int j_mid = m / 2;
while ((i_low + 1) < i_high)
{
int i_mid = (i_low + i_high) / 2;

// element found
if (mat[i_mid][j_mid] == x)
{
System.out.println ( "Found at (" + i_mid +", " + j_mid +")");
return;
}

else if (mat[i_mid][j_mid] > x)


i_high = i_mid;

else
i_low = i_mid;
}

// If element is present on
// the mid of the two rows
if (mat[i_low][j_mid] == x)
System.out.println ( "Found at (" + i_low + "," + j_mid +")");
else if (mat[i_low + 1][j_mid] == x)
System.out.println ( "Found at (" + (i_low + 1) + ", " + j_mid +")");

// Search element on 1st half of 1st row


else if (x <= mat[i_low][j_mid - 1])
binarySearch(mat, i_low, 0, j_mid - 1, x);

36
Unit 3: ARRAYS
// Search element on 2nd half of 1st row
else if (x >= mat[i_low][j_mid + 1] && x <= mat[i_low][m - 1])
binarySearch(mat, i_low, j_mid + 1, m - 1, x);

// Search element on 1st half of 2nd row


else if (x <= mat[i_low + 1][j_mid - 1])
binarySearch(mat, i_low + 1, 0, j_mid - 1, x);

// search element on 2nd half of 2nd row


else
binarySearch(mat, i_low + 1, j_mid + 1, m - 1, x);
}

// Driver program
public static void main (String[] args)
{
int n = 4, m = 5, x = 8;
int mat[][] = {{0, 6, 8, 9, 11},
{20, 22, 28, 29, 31},
{36, 38, 50, 61, 63},
{64, 66, 100, 122, 128}};

sortedMatrixSearch(mat, n, m, x);

}
}

Output:
Found at (0,2)

Search in a row wise and column wise sorted matrix


Given an n x n matrix and a number x, find the position of x in the matrix if it is present in it.
Otherwise, print “Not Found”. In the given matrix, every row and column is sorted in
increasing order. The designed algorithm should have linear time complexity.
Example:
Input: mat[4][4] = { {10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};
x = 29
Output: Found at (2, 1)
Explanation: Element at (2,1) is 29

Input : mat[4][4] = { {10, 20, 30, 40},


{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};

37
Unit 3: ARRAYS
x = 100
Output : Element not found
Explanation: Element 100 is not found

Simple Solution
Approach: The simple idea is to traverse the array and to search element one by one.

Algorithm:
Run a nested loop, outer loop for row and inner loop for the column
Check every element with x and if the element is found then print “element found”
If the element is not found, then print “element not found”.

A better solution is to use Divide and Conquer to find the element which has a time
complexity of O(n1.58). Please refer here for details.

Efficient Solution
Approach: The simple idea is to remove a row or column in each comparison until an
element is found. Start searching from the top-right corner of the matrix. There are three
possible cases.
The given number is greater than the current number: This will ensure, that all the
elements in the current row are smaller than the given number as the pointer is already at the
right-most element and the row is sorted. Thus, the entire row gets eliminated and continue
the search on the next row. Here elimination means that row needs not to be searched.
The given number is smaller than the current number: This will ensure, that all the
elements in the current column are greater than the given number. Thus, the entire column
gets eliminated and continue the search on the previous column i.e. the column at the
immediate left.
The given number is equal to the current number: This will end the search.
The search can also be started from the bottom left corner of the matrix.
Algorithm:
Let the given element be x, create two variable i = 0, j = n-1 as index of row and column
Run a loop until i = 0
Check if the current element is greater than x then decrease the count of j. Exclude the current
column.
Check if the current element is less than x then increase the count of i. Exclude the current
row.
If the element is equal then print the position and end.

Implementation:
// JAVA Code for Search in a row wise and
// column wise sorted matrix

class GFG {

/* Searches the element x in mat[][]. If the


element is found, then prints its position

38
Unit 3: ARRAYS
and returns true, otherwise prints "not found"
and returns false */
private static void search(int[][] mat, int n, int x)
{

int i = 0, j = n - 1; // set indexes for top right


// element

while (i < n && j >= 0) {


if (mat[i][j] == x) {
System.out.print("n Found at " + i + " " + j);
return;
}
if (mat[i][j] > x)
j--;
else // if mat[i][j] < x
i++;
}

System.out.print("n Element not found");


return; // if ( i==n || j== -1 )
}
// driver program to test above function
public static void main(String[] args)
{
int mat[][] = { { 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 27, 29, 37, 48 },
{ 32, 33, 39, 50 } };

search(mat, 4, 29);
}
}

Application
1. Write Java statements that does the following. Write your answer on the space provided
for each item.
a. Declare an array alpha of 10 rows and 20 columns of type int.

________________________________________________________________
b. Initialize each element of the array alpha to 5.

________________________________________________________________
c. Store 1 in the first row and 2 in the remaining rows.

________________________________________________________________
d. Store 5 in the first column, and the value in each remaining column is
39
Unit 3: ARRAYS
twice the value of the previous column.

________________________________________________________________
e. Print the array alpha one row per line.

________________________________________________________________
f. Print the array alpha one column per line.

________________________________________________________________

2. Write a program that allows the user to enter the last names of five candidates in a
local election and the votes received by each candidate. The program should then
output each candidate’s name, the votes received by that candidate, and the
percentage of the total votes received by the candidate. Your program should also
output the winner of the election. A sample output is:

Candidate Votes Received % of Total Votes


Johnson 5000 25.91
Miller 4000 20.72
Duffy 6000 31.09
Robinson 2500 12.95
Ashtony 1800 9.33
Total 19300
The Winner of the Election is Duffy.

40
Unit 3: ARRAYS

Feedback
1. Consider the following declaration
int[][] beta = new int[3][3];
What is stored in beta after each of the following statements executes? Write your
answer on the space provided for each item.
a. for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
beta[i][j] = 0;

_________________________
b. for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
beta[i][j] = i + j;

_________________________
c. for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
beta[i][j] = i * j;

_________________________
d. for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
beta[i][j] = 2 * (i + j) % 4;
_________________________
2. Determine the output of the following programs.
a) public static void main(String[] args) {
int matrix [][]= new int [3][3] ;
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[row].length;col++)
{
matrix[row][col]=1;
System.out.printf("%5d",matrix[row][col]);
}
System.out.println();

41
Unit 3: ARRAYS
}
}
Output:

b) public static void main(String[] args) {


int board [][]= {{02, 03, 01}, {15, 25,
13}, {20, 04, 07}, {11, 18, 14}};

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


{
for (int col = 0; col < board[row].length;col++)
{
System.out.printf("%5d", board[row][col]);
}
System.out.println();
}

int row=3;
int m=board[row][0];

for (int col = 1; col < board[row].length;col++)


{
if (m < board[row][col])
m = board[row][col];
}
System.out.println();

System.out.println("Largest at Row "+(row+1)+ " is "+m);

Output:

3, Multiple Choice. Read the following statements carefully. Choose the best answer from
the choices. Write the letter of your choice on the space provided for before each item.

______ a. Which of the following is a correct way to declare a multidimensional array in


Java?
a) int[] arr; b) int arr[[]];

42
Unit 3: ARRAYS
c) int[][]arr; d) int[[]] arr;

______ b. Which of the following statements is TRUE about MultiDimensional arrays?


a. It can be defined in simple words as array of arrays.
b. Data in multidimensional arrays are stored in tabular form (in row major
order).
c. A & B
d. None of the above.

_____ c. Which of the following multidimensional array declaration is written


correctly?
a. int[][] numbers = new int[3][5];
b. int[][][] threeD_arr = new int[10][20][30];
c. double[ ][ ] values = new double [2][4];
d. All of the above.

_____ d. Given the following:


long [][] stuff ;
Which of the following statements constructs an array with 5 rows of 7
columns each and assign its reference to stuff?
a. stuff = new stuff[5][7] ;
b. stuff = new long[5][7] ;
c. stuff = long[5][7] ;
d. stuff = long[7][5] ;

_____ e. Examine the following:


double[][] values =
{ {1.2, 9.0, 3.2},
{9.2, 0.5, -1.2},
{7.3, 7.9, 4.8} } ;
what is in values[2][1] ?
a. 7.9
b. 7.3
c. 9.2
d. 0.5

_____ f. Which BEST describes an array?


a. A data structure - Stores a collection of values under one name
b. A list - Stores a list of numbers
c. A data collection - Stores a structure of values under one name
d. A list - Stores a list of strings

_____ g. Each element in an array can be accessed using its what?


a. By counting in the items in the array
b. Position or index in the array
c. By printing the items in the array
d. By printing and counting the entire array

_____ h. How many columns does a have if it is created as follows


int[][] a = {{2, 4, 6, 8}, {1, 2, 3, 4}};?

43
Unit 3: ARRAYS
a. 3
b. 4
c. 2
d. 1

Reflection

Now that we have finished about arrays, why do you think arrays are useful in
programming?

Summary of the Unit

 An array is a structured data type with a fixed number of elements. Every


element is of the same type, and the elements are accessed using their
relative positions in the array.
 Elements of a one-dimensional array are arranged in the form of a list.
 An array index can be any expression that evaluates to a nonnegative integer. The
value of the index must always be less than the size of the array.
 In Java, an array index starts with 0.
 In Java, [] is an operator, called the array subscripting operator. When an array object
is instantiated, its elements are initialized to their default values.
 Arrays that are created, that is, instantiated, during program execution are called
dynamic arrays.
 Arrays can be initialized when they are created.
 A public (final) instance variable length is associated with each array that has been
instantiated (that is, for which memory has been allocated to
 A two-dimensional array is an array in which the elements are arranged in a table
form.
 To access an element of a two-dimensional array, you need a pair of indices: one for
the row position and one for the column position. store the data). The variable length
contains the size of the array.

44
Unit 3: ARRAYS
 In row processing, a two-dimensional array is processed one row at a time.
 In column processing, a two-dimensional array is processed one column at a time.
 Java stores two-dimensional arrays in a row order form in computer memory.

References

Data Structures and Algorithms in Java Michael T. Goodrich Department of Computer


Science University of California, Irvine 1 Roberto Tamassia Department of Computer
Science Brown University 0-471-73884-0 Fourth Edition
Java Programming From Program Analysis to Program Design, D. S. Malik, Fourth Edition
Retrieved from https://www.geeksforgeeks.org/multidimensional-arrays-in-java/
Retrieved from https://algorithms.tutorialhorizon.com/sort-the-two-dimensional-2d-array-
in-place/
Retrieved from https://www.geeksforgeeks.org/search-element-sorted-matrix/
Retrieved from https://www.geeksforgeeks.org/search-in-row-wise-and-column-wise-sorted-
matrix/

45

You might also like