DSA Module 3 Arrays 4weeks
DSA Module 3 Arrays 4weeks
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.
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
Presentation of Contents
One-Dimensional Array
A one-dimensional array is an array in which the elements are arranged in a list form.
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:
The statement:
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
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:
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.
3
Unit 3: ARRAYS
arrayName[indexExp]
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.
list[5] = 34;
stores 34 into list[5], which is the sixth element of the array list as shown below.
list[3] = 63;
is equivalent to the assignment statements:
i = 3;
list[i] = 63;
list[2 * i - 3] = 58;
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].
The following statements illustrate this concept (suppose that console is a Scanner
object initialized to the standard input device):
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.
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.
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.
This statement creates the array list of six elements and initializes the elements using
the values given. Here, list.length is 6.
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.
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.
The following for loop steps through each element of the array list, starting at the first
element of list:
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:
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:
The following example shows how loops are used to process arrays. The following
declaration is used throughout this example:
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.
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:
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.
3. Printing an array: The following loop outputs the elements of array sales. For
simplicity, we assume that the output goes to the screen.
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;
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.
9
Unit 3: ARRAYS
Algorithm:
Let's see an example of linear search in java where we are going to search an element sequentially
from an array.
Output:
50 is found at index: 3
import java.util.Scanner;
class LinearSearchExample2
{
public static void main(String args[])
{
10
Unit 3: ARRAYS
int c, n, search, array[];
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
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 elements.
System.out.println("Enter " +n+ " Numbers : ");
for(i=0; i<n; i++)
{
arr[i] = scan.nextInt();
}
Output
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
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 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
14
Unit 3: ARRAYS
15
Unit 3: ARRAYS
{
// we find the mid value in the search space and
// compares it with key value
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.
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:
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
Presentation of Contents
Examples:
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.
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 } };
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
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 } };
Output:
arr[0][0] = 1
22
Unit 3: ARRAYS
Example:
class GFG {
public static void main(String[] args)
{
int[][] arr = { { 1, 2 }, { 3, 4 } };
Output:
12
34
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
Output:
arr[0][0][0] = 1
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 } } };
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
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 } } };
Output:
arr[0][0][0] = 1
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 } } };
System.out.println();
}
System.out.println();
}
}
}
class GFG {
public static void main(String[] args)
{
int[][][] arr = { { { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } } };
Output:
12
34
26
Unit 3: ARRAYS
56
78
Implementation:
import java.util.Scanner;
// totalTestCases = total
// number of TestCases
// eachTestCaseValues =
// values in each TestCase as
// an Array values
int totalTestCases, eachTestCaseValues;
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.
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);
}
//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;
32
Unit 3: ARRAYS
//row is sorted, no need to check further
break;
}
}
}
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:
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.
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)
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
class GFG
{
static int MAX = 100;
// Element found
if (mat[i][j_mid] == x)
{
System.out.println ( "Found at (" + i + ", " + j_mid +")");
return;
}
else
j_low = j_mid + 1;
}
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;
}
// element found
if (mat[i_mid][j_mid] == x)
{
System.out.println ( "Found at (" + i_mid +", " + j_mid +")");
return;
}
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 +")");
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);
// 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)
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 {
38
Unit 3: ARRAYS
and returns true, otherwise prints "not found"
and returns false */
private static void search(int[][] mat, int n, int x)
{
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:
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:
int row=3;
int m=board[row][0];
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.
42
Unit 3: ARRAYS
c) int[][]arr; d) int[[]] arr;
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?
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
45