Model G20 2027 at FLAME University, registrations now open

Arrays | ICSE Class 10 Computer Applications Notes

30 min read

On this page

This note covers array definitions and uses, declaration and initialisation, indices and length, input and traversal, bubble sort, selection sort, linear search, binary search, two-dimensional arrays, matrix display, and row, column and diagonal sums in Java.

What is an array, and why is it useful?

Definition: An array is a fixed-length collection of elements of one declared component type, accessed through a common name and integer indices. An element is an individual stored value; an index identifies its place in the array.

A data type specifies the kind of value a program can store. Java's int type stores integers, which are whole numbers including negative values and zero. An int array groups integer values so that one operation can be repeated across them.

A variable is a named storage location. A single integer variable holds one integer value. An array variable holds a reference, which identifies an array object. The object contains the indexed elements. The array name and one index identify a particular element.

How is an array a composite type?

A primitive type represents a basic value, such as an int. A composite type groups components into a larger structure. An array is composite because it brings multiple elements together. The component type determines what can be assigned to each element.

Arrays help a program store related values, visit them systematically, calculate totals, arrange values into order and locate a requested value. One indexed loop can perform the same operation on successive elements without requiring a different variable name for every value.

A one-dimensional array is accessed using one index. A two-dimensional array uses two indices to reach an individual value. For a rectangular arrangement, these identify a row and a column. A row runs horizontally; a column runs vertically.

What does fixed length mean?

The number of elements in an array object is fixed when that object is created. The values stored in its elements can change. Replacing an element therefore changes its contents without changing the array's length or the range of valid indices.

Note: Keep three ideas separate: the array reference identifies the object, an index selects an element, and the selected element holds a value. An element's value does not determine its index.

How are arrays declared, initialised and indexed?

Declaration introduces a variable's name and type. Creation makes the array object. Initialisation supplies its starting contents. These are related operations, but an array variable declaration alone does not create storage for its elements.

Syntax: int[] a; declares a as a reference to an integer array. The square brackets [] denote an array type. The statement a = new int[6]; creates six integer elements and assigns the reference to a. The new operator creates the array object.

The assignment symbol = places the value on its right into the variable or element on its left. A semicolon ; ends a statement. Newly created int array elements have the default value zero, meaning the starting value supplied automatically before explicit element assignments.

An initialiser is a list of starting values inside braces {}. Commas separate those values. In int[] a = {2, 4, 6, 8, 10, 12}; the list determines the array length. Here a is the array variable used in the following program.

How do length and the last index differ?

Java indices begin at zero. If n denotes an array's length, its valid indices run from 0 to n - 1. The minus symbol subtracts. The expression a.length gives the number of elements; the dot selects the array's length field, a named property.

The array expression a[0] selects its first element. The expression a[a.length - 1] selects its last element when the array is non-empty. Access beyond the valid range causes an ArrayIndexOutOfBoundsException, a runtime error raised when the program executes an invalid access.

How should the program wrapper be read?

A class defines a Java type. Each program below uses the class name ArraysDemo. The public keyword permits access; static makes main a class method; void means it returns no value. A method is a named block of executable instructions.

The main method is the program's entry point. Its String[] args parameter receives command-line text arguments; String represents text, and args names that array. Parentheses enclose parameters or method arguments. Braces delimit blocks. System.out.println prints a value and then starts a new output line.

Worked example 1. Display the length, first value and last value of the given integer array.

class ArraysDemo {
public static void main(String[] args) {
int[] a = {2, 4, 6, 8, 10, 12};
System.out.println(a.length);
System.out.println(a[0]);
System.out.println(a[a.length - 1]);
}
}

Answer: The output is:
6
2
12

  1. Line 1 opens the ArraysDemo class; line 2 opens its main method, where execution begins.
  2. Line 3 creates a six-element integer array and initialises its values in the written order.
  3. Line 4 prints its length, 6. This counts elements rather than reporting the last index.
  4. Line 5 uses index 0 and prints 2. Line 6 uses the last index, 5, and prints 12.
  5. Lines 7 and 8 close the method and class blocks. No input is needed for this program.

How can a loop accept and traverse array data?

Traversal means visiting successive elements to perform an operation. A loop repeats instructions. In a for loop, an initialisation runs first, a condition is checked before each repetition, and an update runs after that repetition. A counter tracks the current index.

In for (int i = 0; i < a.length; i++), i is the integer index counter. The operator < means less than, and ++ increases i by one. Starting at zero and stopping before the length visits every valid index.

How is input stored?

Scanner is a Java class for reading input. The import statement makes the class name available from the java.util package, a grouping of related classes. System.in supplies standard input, and nextInt() reads the next integer. The variable sc names the Scanner object.

Store each input value in a[i], not in the index variable i. The counter selects the destination element; nextInt() supplies its contents. A second loop can display the stored data after the input loop finishes. System.out.print displays without adding a new line.

Worked example 2. Accept six integers and display them in their original order. Double quotation marks delimit a String literal, or fixed text; " " is one space.

Input: 2 4 6 8 10 12

import java.util.Scanner;
class ArraysDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] a = new int[6];
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}

Answer: The output is:
2 4 6 8 10 12

  1. Line 1 imports Scanner. Lines 2 and 3 open the class and its main method.
  2. Line 4 creates the input reader sc. Line 5 creates an array with six integer elements.
  3. Line 6 starts the input loop. Line 7 stores the next integer at index i; line 8 closes that loop.
  4. Line 9 starts a new traversal. Line 10 prints each element followed by a space; + joins a value to the space String.
  5. Line 11 closes the output loop. Lines 12 and 13 close main and the class. The displayed sequence has a trailing space.

Rule: Use i < a.length for a forward traversal beginning at zero. The condition i <= a.length includes the invalid index a.length; <= means less than or equal to.

How does bubble sort arrange an array?

Sorting arranges elements into a chosen order. Ascending order runs from smaller to larger values; descending order runs from larger to smaller values. Bubble sort compares adjacent elements, which are neighbours, and swaps them when they are in the wrong order.

Result: Each ascending bubble-sort pass places the largest remaining value

A swap exchanges two values. A pass is one sweep through the required comparisons. In ascending bubble sort, a left-to-right pass moves the largest remaining value to the right-hand end of the unsorted part. Later passes exclude the values already placed.

Which variables control the comparisons?

Here n stores the array length, pass counts completed passes, j selects the left element of an adjacent pair, and temp temporarily holds a value during a swap. The operator > means greater than. An if statement executes its block when its condition is true.

Rule: With pass starting at zero, compare a[j] with a[j + 1] while j < n - 1 - pass. The + operator adds numbers here. Reducing the bound leaves the already placed end elements untouched.

Worked example 3. Sort the given array into ascending order by bubble sort.

class ArraysDemo {
public static void main(String[] args) {
int[] a = {8, 7, 13, 1, -9, 4};
int n = a.length;
for (int pass = 0; pass < n - 1; pass++) {
for (int j = 0; j < n - 1 - pass; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
}
}

Answer: The output is:
-9 1 4 7 8 13

  1. Lines 1 and 2 open the program. Line 3 supplies the data, and line 4 records its length.
  2. Line 5 controls the passes. Line 6 moves through adjacent pairs in the remaining unsorted part.
  3. Line 7 checks whether the left value exceeds the right value. An ordered pair needs no swap.
  4. Line 8 saves the left value; line 9 replaces it with the right value; line 10 restores the saved value on the right.
  5. Lines 11 to 13 close the condition and both sorting loops. Lines 14 and 15 traverse and print the result.
  6. Lines 16 to 18 close the output loop, method and class. Every printed number is followed by a space.

What the figure shows

Bubble-sort comparisons

Rows of boxes show 8, 7, 13, 1, -9 and 4 with indices below the starting row. Arrows connect successive comparisons. Blue shading marks compared elements; green shading marks elements already sorted. Swap and No Change label the actions.

See Fig. 5.1 in your NCERT textbook

The first pass leaves 7, 8, 1, -9, 4, 13. The array becomes sorted during the fourth pass. This fixed-pass program still performs the fifth pass. A version that checks whether a whole pass made no swaps can stop at that point.

How does selection sort differ from bubble sort?

Property: Selection sort grows a sorted prefix

Selection sort finds the smallest value in the unsorted part and places it at that part's beginning. The left part grows into a sorted prefix, meaning a sorted group at the start. The remaining right part still needs to be processed.

In the program below, i identifies the position to fill next. The variable min stores the index of the smallest value found so far; it does not store that value. The counter j checks the remaining candidates, and temp preserves a value during exchange.

Why must the minimum index be reset?

At the start of each pass, min = i treats the first unsorted element as the current candidate. Comparing subsequent values can replace that candidate. After all candidates have been checked, one exchange puts the selected minimum at i.

Worked example 4. Sort the same original data using selection sort.

class ArraysDemo {
public static void main(String[] args) {
int[] a = {8, 7, 13, 1, -9, 4};
for (int i = 0; i < a.length - 1; i++) {
int min = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[min]) {
min = j;
}
}
int temp = a[i];
a[i] = a[min];
a[min] = temp;
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}

Answer: The output is:
-9 1 4 7 8 13

  1. Lines 1 and 2 open the class and main; line 3 creates the original unsorted array.
  2. Line 4 chooses each position to fill. Line 5 resets the minimum candidate to that position.
  3. Line 6 scans later indices. Line 7 compares their values with the candidate; line 8 saves a better candidate index.
  4. Lines 9 and 10 close the comparison and scan. Lines 11 to 13 exchange the selected minimum with a[i].
  5. Line 14 closes the pass. Lines 15 and 16 traverse and print the sorted array, with a trailing space.
  6. Lines 17 to 19 close the printing loop, method and class. Swapping an element with itself leaves it unchanged.

Table: Comparison of the sorting methods

FeatureBubble sortSelection sort
ComparisonAdjacent valuesCandidate minimum against later values
ExchangeAfter an out-of-order adjacent comparisonAfter the minimum search in each pass
Ascending result of a passLargest remaining value placed at the rightSmallest remaining value placed at the left
Part omitted nextAlready placed right endAlready placed left end

How does linear search find a value?

Searching determines whether a requested element occurs in a collection and can report where it occurs. The requested value is usually called the key. Linear search, also called sequential search, checks elements in order from the beginning until a match is found.

Property: An unsuccessful linear search checks every element

If no match occurs, the search must reach the end before reporting failure. A mismatch at one index says nothing about later indices. Linear search can be applied to unordered data, so sorting is not a prerequisite for this method.

How is success recorded?

Here key stores the requested value and pos stores its found index. The initial value -1 is a sentinel, a special value representing “not found”. It cannot be a valid Java array index. The operator == tests equality; it does not assign a value.

Worked example 5. Find the key 17 by linear search and display its zero-based index.

class ArraysDemo {
public static void main(String[] args) {
int[] a = {8, -4, 7, 17, 0, 2, 19};
int key = 17, pos = -1;
for (int i = 0; i < a.length; i++) {
if (a[i] == key) {
pos = i;
break;
}
}
System.out.println(pos);
}
}

Answer: The output is:
3

  1. Lines 1 and 2 open the program. Line 3 supplies the array; line 4 sets the key and the not-found sentinel.
  2. Line 5 visits successive indices. Line 6 checks the current element for equality with key.
  3. Line 7 records the matching index. Line 8 uses break, which exits the nearest enclosing loop.
  4. Lines 9 and 10 close the condition and loop. Line 11 prints the recorded index, 3.
  5. Lines 12 and 13 close main and the class. Values 8, -4 and 7 fail before 17 matches on the fourth comparison.

Note: Index and ordinary position differ. The found value has index 3 but position 4 when positions are counted from one. Add one to a found index only when reporting a position; preserve the not-found case separately.

This implementation stops at its first match. Finding every matching occurrence would require continuing the scan. For an absent key, pos stays -1. Keep a single final failure decision after the search instead of declaring failure inside the loop after each mismatch.

How does binary search reduce the search area?

Binary search uses sorted order to discard part of the search area after checking a middle element. The following version requires ascending order. The variables first and last are the inclusive indices of the current search area; inclusive means both endpoints are included.

The variable mid stores the middle index. For non-negative integer bounds, (first + last) / 2 uses integer division, which discards the fractional part. Recalculate mid each time the bounds change. The array itself remains unchanged during the search.

Which half remains after a mismatch?

If a[mid] exceeds key, keep the lower half by setting last to mid - 1. If a[mid] is below key, keep the upper half by setting first to mid + 1. Equality finishes the search. When first exceeds last, no candidate remains.

Worked example 6. Search for 2 in the given ascending array. The else branch runs when its preceding if condition is false.

class ArraysDemo {
public static void main(String[] args) {
int[] a = {2, 3, 5, 7, 10, 11, 12, 17, 19, 23, 29, 31, 37, 41, 43};
int key = 2, first = 0, last = a.length - 1, pos = -1;
while (first <= last) {
int mid = (first + last) / 2;
if (a[mid] == key) {
pos = mid;
break;
} else if (a[mid] > key) {
last = mid - 1;
} else {
first = mid + 1;
}
}
System.out.println(pos);
}
}

Answer: The output is:
0

  1. Lines 1 and 2 open the program. Line 3 provides sorted data; line 4 initialises the key, bounds and result.
  2. Line 5 starts a while loop, repeating while its condition is true. Line 6 recalculates the middle index.
  3. Line 7 tests equality. Lines 8 and 9 record the index and stop searching when the key matches.
  4. Line 10 tests whether the middle value is too large. Line 11 removes that value and the upper half.
  5. Lines 12 and 13 handle a middle value that is too small by removing it and the lower half.
  6. Lines 14 and 15 close the branches and loop. Line 16 prints index 0; lines 17 and 18 close the program.

The middle indices are 7, 3, 1 and 0, with values 17, 7, 3 and 2. Four iterations, meaning repetitions of the loop body, find the key at index zero. The initial bounds are 0 and 14; the upper bound then becomes 6, 2 and 0.

Rule: Binary search needs sorted data and bound updates that match its order. After a mismatch, exclude the middle element already checked. Using mid itself as the next bound can leave the search area unchanged.

How are two-dimensional arrays entered and displayed?

A matrix is a rectangular arrangement of values in rows and columns. Java represents a two-dimensional array as an array whose elements are themselves arrays. For matrix work here, each row has the same number of columns, giving a rectangular array.

Syntax: int[][] a = new int[2][3]; creates two rows with three integer elements in each row. In a[r][c], r is the row index and c is the column index. The first index selects the row; the second selects its element.

The expression a.length gives the row count. The expression a[r].length gives the element count in row r. These lengths answer different questions. Using the row count as a column bound can miss elements or cause an invalid access in a non-square matrix.

Why are nested loops needed?

Nested loops place one loop inside another. An outer row loop chooses a row, while an inner column loop visits that row's elements. Reading row by row is called row-wise input. Display follows the same order and starts a new line after each row.

Worked example 7. Read the six supplied values row by row into a two-row, three-column matrix, then display it.

Input: 8 7 13 1 -9 4

import java.util.Scanner;
class ArraysDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[][] a = new int[2][3];
for (int r = 0; r < a.length; r++) {
for (int c = 0; c < a[r].length; c++) {
a[r][c] = sc.nextInt();
}
}
for (int r = 0; r < a.length; r++) {
for (int c = 0; c < a[r].length; c++) {
System.out.print(a[r][c] + " ");
}
System.out.println();
}
}
}

Answer: The output is:
8 7 13
1 -9 4

  1. Line 1 imports Scanner; lines 2 and 3 open the class and method. Line 4 creates the input reader.
  2. Line 5 creates the rectangular array. Line 6 chooses a row; line 7 chooses each column within it.
  3. Line 8 stores the next integer at the selected row and column. Lines 9 and 10 close the input loops.
  4. Lines 11 and 12 traverse the same rows and columns again. Line 13 prints one matrix value and a space.
  5. Line 14 closes the column loop. Line 15 starts a new line after the complete row has printed.
  6. Lines 16 to 18 close the row loop, main and class. Each displayed row has a trailing space.

Draw and label

Matrix indices

Draw two rows and three columns. Put 8, 7 and 13 across row 0, and 1, -9 and 4 across row 1. Label the columns 0, 1 and 2. Mark a[1][2] at the value 4.

How are row sums and column sums calculated?

An accumulator is a variable that collects a running result, such as a sum. Start it at zero before adding the required elements. The shorthand operator += adds the right-hand value to the variable on the left and stores the result there.

For a row sum, keep the row index fixed while the column index changes. For a column sum, keep the column index fixed while the row index changes. The addition is similar, but the order and purpose of the loops differ.

Where should the accumulator be reset?

Reset sum inside the outer loop and before the inner loop. Each new row or column then starts its own total. Resetting it inside the inner loop would discard earlier additions. Resetting it before all the loops would combine totals from different rows or columns.

Worked example 8. Print each row sum, followed by each column sum, for the fully specified matrix. Nested braces give the values of each row.

class ArraysDemo {
public static void main(String[] args) {
int[][] a = {{8, 7, 13}, {1, -9, 4}};
for (int r = 0; r < a.length; r++) {
int sum = 0;
for (int c = 0; c < a[r].length; c++) {
sum += a[r][c];
}
System.out.println(sum);
}
for (int c = 0; c < a[0].length; c++) {
int sum = 0;
for (int r = 0; r < a.length; r++) {
sum += a[r][c];
}
System.out.println(sum);
}
}
}

Answer: The output is:
28
-4
9
-2
17

  1. Lines 1 and 2 open the program. Line 3 initialises both rows of the rectangular array.
  2. Line 4 chooses a row. Line 5 starts its sum at zero; line 6 visits its columns.
  3. Line 7 adds the selected element; line 8 ends the inner loop. Line 9 prints that row total.
  4. Line 10 closes the row loop. Line 11 chooses each column using the first row's length.
  5. Line 12 resets the column total. Line 13 visits the rows, and line 14 adds their elements in the chosen column.
  6. Line 15 closes the inner loop; line 16 prints the column total. Lines 17 to 19 close the remaining blocks.

The row calculations are 8 + 7 + 13 = 28 and 1 + (-9) + 4 = -4. The column calculations are 8 + 1 = 9, 7 + (-9) = -2 and 13 + 4 = 17. Parentheses group the negative value in this arithmetic.

How are the two diagonal sums found?

A square matrix has equal numbers of rows and columns. Its main diagonal runs from top left to bottom right. Its other diagonal runs from top right to bottom left. These directions identify the two diagonals unambiguously.

For a square array a of size n by n, n denotes both its row count and column count. The main-diagonal elements have equal row and column indices, so they are a[i][i]. Here i is the row index, changing from zero to n - 1.

Rule: The opposite diagonal uses a[i][n - 1 - i]. As the row index increases by one, the column index decreases by one. Equivalently, the row and column indices add to n - 1.

How are the totals kept separate?

Use mainSum for the top-left to bottom-right total and otherSum for the top-right to bottom-left total. Initialise both to zero. A single loop can add one element from each diagonal per repetition, without scanning every element in the matrix.

Worked example 9. Find both diagonal sums of the square matrix with rows {10, 20} and {30, 40}.

class ArraysDemo {
public static void main(String[] args) {
int[][] a = {{10, 20}, {30, 40}};
int n = a.length, mainSum = 0, otherSum = 0;
for (int i = 0; i < n; i++) {
mainSum += a[i][i];
otherSum += a[i][n - 1 - i];
}
System.out.println(mainSum);
System.out.println(otherSum);
}
}

Answer: The output is:
50
50

  1. Lines 1 and 2 open the program. Line 3 gives the complete square matrix; line 4 records its size and initialises both sums.
  2. Line 5 visits each row index. Line 6 adds the element whose column index equals its row index.
  3. Line 7 adds the element whose column index is n - 1 - i. Line 8 ends the traversal.
  4. Line 9 prints 10 + 40, giving 50. Line 10 prints 20 + 30, also giving 50.
  5. Lines 11 and 12 close the program. Equal totals here are a result of these data, not a general rule for square matrices.

When a square matrix has an odd number of rows, the central element belongs to both diagonals. Include it in each total when calculating two separate diagonal sums. If instead counting each element in their combined collection once, the shared centre must not be counted twice.

Check the shape first. The expressions above describe the two full corner-to-corner diagonals of a square matrix. A rectangular matrix still supports row and column totals, but its row count alone does not establish the square-matrix diagonal conditions used here.

Glossary

  • Array — A fixed-length collection of indexed elements with one declared component type.
  • Element — An individual value stored at a particular indexed place in an array.
  • Index — An integer identifying an element's place, starting at zero in Java arrays.
  • Length — The number of elements in an array, obtained through its length field.
  • Initialisation — Supplying starting values to variables or array elements before processing them.
  • Traversal — Visiting successive elements of a collection to carry out an operation.
  • Pass — One sweep through the comparisons required by a particular sorting stage.
  • Swap — An exchange that places each of two stored values in the other's position.
  • Search key — The requested value compared with collection elements during a search.
  • Sentinel — A special value used to represent a condition such as an unsuccessful search.
  • Accumulator — A variable that stores a running result as further values are processed.
  • Matrix — A rectangular arrangement of values organised into horizontal rows and vertical columns.
  • Main diagonal — The top-left to bottom-right diagonal, where row and column indices are equal.

Common errors and misconceptions

  • Misconception: Declaring int[] a; creates the elements. Correct: It declares an array reference variable. Create an array and assign that reference before using its elements.
  • Misconception: The last index equals a.length. Correct: For a non-empty array, the last index is a.length - 1 because indexing begins at zero.
  • Misconception: Write a.length() to find an array's size. Correct: Use a.length. The array length is a field, whereas parentheses are used when calling a method.
  • Misconception: Assigning a[j] = a[j + 1] completes a swap. Correct: Save the original left value first, then complete both assignments so that neither value is lost.
  • Misconception: A mismatch proves a linear search unsuccessful. Correct: Later elements may match. Report failure after all required elements have been checked without success.
  • Misconception: Binary search can discard half of any array. Correct: Its decisions rely on sorted order and on bounds that match that order.
  • Misconception: A matrix's length is its column count. Correct: a.length counts rows. The length of a selected row supplies its column count.
  • Misconception: One unrestarted sum gives separate row totals. Correct: Reset the accumulator before processing each row, and print after completing that row.

Exam-style questions with model answers

Q1. Define an array in Java and explain why it is a composite type. [2 marks]
  1. An array is a fixed-length collection of elements of one declared component type, accessed using integer indices.
  2. It is a composite type because it groups multiple indexed elements into one structure, rather than representing a single primitive value.
Q2. Given int[] a = {2, 4, 6, 8, 10, 12}; state a.length, the last valid index and a[3]. Explain each result. [3 marks]
  1. The value of a.length is 6 because the initialiser contains six elements. Length counts all elements in the array.
  2. The last valid index is 5. Indexing begins at zero, so the final index is one less than the length.
  3. The value of a[3] is 8. Index 3 selects the fourth element in the given initialiser, not its third element.
Q3. Apply one complete left-to-right ascending bubble-sort pass to {8, 7, 13, 1, -9, 4}. Compare adjacent pairs, swapping only if the left value is greater. Give the array after each of the five comparisons. [5 marks]
  1. Compare 8 and 7. Since 8 is greater, exchange them. The array becomes {7, 8, 13, 1, -9, 4}; the next comparison uses 8 and 13.
  2. Compare 8 and 13. They are already in ascending order, so do not exchange them. The array remains {7, 8, 13, 1, -9, 4}.
  3. Compare 13 and 1. Exchange this pair because 13 is greater. The array becomes {7, 8, 1, 13, -9, 4}.
  4. Compare 13 and -9. Exchange this pair, placing the smaller value first. The array becomes {7, 8, 1, -9, 13, 4}.
  5. Compare 13 and 4. Exchange them to obtain {7, 8, 1, -9, 4, 13}. The largest value is now at the end.
Q4. Trace ascending selection sort on {8, 7, 13, 1, -9, 4} for its first pass. Select the minimum from the entire unsorted part, then make one swap. State the minimum, its original index, the exchange and the resulting array. [4 marks]
  1. The smallest value is -9. The first pass compares candidate values across the entire original array before carrying out its final exchange.
  2. The minimum has original index 4, because the indices of the six given elements begin at zero.
  3. Exchange the element at index 4 with the element at index 0. Thus -9 and 8 change places.
  4. The resulting array is {-9, 7, 13, 1, 8, 4}. The first position is now fixed for ascending selection sort.
Q5. Use linear search from the beginning of {8, -4, 7, 17, 0, 2, 19} for key 17, stopping at the first match. State the compared values, number of comparisons, index and position counted from one. [4 marks]
  1. The values compared with 17 are 8, -4, 7 and 17, in that order. The later elements need not be examined.
  2. There are four comparisons. The first three values fail the equality test, while the fourth value matches the key.
  3. The found index is 3, since the first element is at index zero and the matching element is fourth.
  4. The position counted from one is 4. It is obtained by adding one to the found index, after confirming success.
Q6. Search for key 2 in {2, 3, 5, 7, 10, 11, 12, 17, 19, 23, 29, 31, 37, 41, 43}. Use ascending binary search with first = 0, last = 14 and mid = (first + last) / 2 using integer division. After a mismatch use last = mid - 1 or first = mid + 1 as appropriate. Explain the order requirement, trace each iteration and state the result. [6 marks]
  1. The array is in ascending order. This allows a comparison with the middle value to rule out one side without checking every element there.
  2. Initially first is 0 and last is 14, so mid is 7. The value 17 exceeds 2; set last to 6.
  3. With bounds 0 and 6, mid is 3. The value 7 exceeds the key 2, so set last to 2.
  4. With bounds 0 and 2, mid is 1. The value 3 exceeds the key 2, so set last to 0.
  5. With bounds 0 and 0, mid is 0. The value at that index is 2, so the equality test succeeds.
  6. The search finishes after four iterations, finding index 0 and position 1. The array contents have not been changed by the search.
Q7. For int[][] a = {{8, 7, 13}, {1, -9, 4}};, find both row sums followed by all three column sums, in index order. Show each addition. [5 marks]
  1. Row 0 contains 8, 7 and 13. Its sum is 8 + 7 + 13 = 28; the row index remains fixed during these additions.
  2. Row 1 contains 1, -9 and 4. Its sum is 1 + (-9) + 4 = -4, calculated with a fresh accumulator.
  3. Column 0 contains 8 and 1. Its sum is 8 + 1 = 9; the row index changes while the column index remains zero.
  4. Column 1 contains 7 and -9. Its sum is 7 + (-9) = -2; the negative value must retain its sign.
  5. Column 2 contains 13 and 4. Its sum is 13 + 4 = 17. The required output order is 28, -4, 9, -2, 17.
Q8. For int[][] a = {{10, 20}, {30, 40}};, give both corner-to-corner diagonal sums. Name each diagonal by direction, identify its elements and show the addition. [2 marks]
  1. The top-left to bottom-right diagonal contains a[0][0] and a[1][1], so its sum is 10 + 40 = 50.
  2. The top-right to bottom-left diagonal contains a[0][1] and a[1][0], so its sum is 20 + 30 = 50.

Key takeaways

  • An array groups indexed elements of one declared component type, and its length stays fixed after creation.
  • Java array indices start at zero, so a non-empty array's final valid index is its length minus one.
  • Use the length field without parentheses, and keep loop conditions within the valid range of indices.
  • Bubble sort exchanges unordered adjacent pairs; selection sort selects the smallest remaining value for the next position.
  • Linear search checks successive elements and needs no preliminary sorting; an unsuccessful search must exhaust the candidates.
  • Binary search uses sorted order, a middle element and updated bounds to reduce the remaining search area.
  • In matrix traversal, row and column indices have separate bounds, and a new output line follows each complete row.
  • Reset accumulators for separate row or column sums; use the appropriate square-matrix index relationships for diagonal sums.

Test yourself

What does int[] a; declare?

It declares an integer-array reference variable; it does not create the array elements.

For int[] a = {2, 4, 6, 8, 10, 12};, what are the length and last valid index?

The length is 6, and the last valid index is 5 because indexing begins at zero.

Why does an array traversal beginning at zero use i < a.length?

The strict less-than condition prevents access at a.length, which lies beyond the last valid index.

Where does the largest value finish after a left-to-right ascending bubble-sort pass?

It finishes at the right-hand end of the part examined during that pass.

What does min store in the selection-sort program?

It stores the index of the smallest candidate found so far, rather than the candidate value itself.

Why must a binary-search array be sorted?

Sorted order makes the middle comparison justify discarding one side of the remaining search area.

For int[][] a = {{8, 7, 13}, {1, -9, 4}};, what are a.length and a[0].length?

The outer length is 2 rows, while the first row contains 3 elements.

In a square array with n rows, which element is opposite a[i][i] on the other diagonal in row i?

The other diagonal uses a[i][n - 1 - i], with the column index decreasing as the row index increases.