Program Flow  «Prev  Next»
Lesson 6Nested Loops
Objective Application of Nested Loops

Java function accepts returns the duplicate element

Write the Java code where the Java function accepts an array of integers as a parameter and returns the duplicate element. To write a Java function that accepts an array of integers as a parameter and returns the duplicate element, you can use a HashSet to store the unique elements and find the duplicates. Here's an example implementation:

import java.util.HashSet;
import java.util.Set;

public class DuplicateFinder {
    public static void main(String[] args) {
        int[] inputArray = {1, 2, 3, 4, 4, 5, 6};
        int duplicate = findDuplicate(inputArray);
        System.out.println("Duplicate element is: " + duplicate);
    }

    public static int findDuplicate(int[] array) {
        Set<Integer> uniqueElements = new HashSet<>();
        
        for (int num : array) {
            if (uniqueElements.contains(num)) {
                return num;
            } else {
                uniqueElements.add(num);
            }
        }
        
        // If no duplicate found, return -1 or throw an exception
        return -1;
    }
}


This code defines a findDuplicate function that accepts an array of integers as its input. The function iterates through the array, adding each element to a HashSet. If an element is already in the HashSet, it means the element is a duplicate, and the function returns the duplicate element. If no duplicate is found, the function returns -1 as an indicator that no duplicate was found. You can also choose to throw an exception instead of returning -1 if you prefer.
Please note that this function assumes that there is only one duplicate element in the array. If there are multiple duplicates or you want to find all the duplicates, you will need to modify the code accordingly.


Matrix Multiplication in Java

Loops can be nested within each other. Any nested combination of the for, for-each, while, or do-while loops is permitted. This is useful for addressing a number of problems. The example that follows computes the sum of the elements of a row in a two-dimensional array. It starts by initializing each element to the sum of its indexes. The array is then displayed. This is followed by nested loops to compute and display the sum of the elements for each row:

final int numberOfRows = 2;
final int numberOfColumns = 3;
int matrix[][] = new int[numberOfRows][numberOfColumns];
for (int i = 0; i lt; matrix.length; i++) {
 for (int j = 0; j < matrix[i].length; j++) {
  matrix[i][j] = i + j;
 }
}
for (int i = 0; i < matrix.length; i++) {
 for(int element : matrix[i]) {
  System.out.print(element + " ");
 }
 System.out.println();
}
for (int i = 0; i < matrix.length; i++) {
 int sum = 0;
 for(int element : matrix[i]) {
  sum += element;
 }
 System.out.println("Sum of row " + i + " is " +sum);
}

Notice the use of the length method used to control the number of times the loops are executed. This makes the code more maintainable if the size of the arrays change. When executed we get the following output:
0 1 2
1 2 3
Sum of row 0 is 3
Sum of row 1 is 6


The break and continue statements can also be used within nested loops. However, they will only be used in conjunction with the current loop. That is, a break out of an inner loop will only break out of the inner loop and not the outer loop. We can break out of the outer loop from an inner loop using labels. In the following modification of the last nested loop sequence, we break out of the inner loop when the sum exceeds 2:

for (int i = 0; i < matrix.length; i++) {
 int sum = 0;
 for(int element : matrix[i]) {
  sum += element;
  if(sum > 2) {
   break;
  }
 }
 System.out.println("Sum of row " + i + " is " +sum);
}

The execution of this nested loop will change the sum of the last row as shown below:
Sum of row 0 is 3
Sum of row 1 is 3

The break statement took us out of the inner loop but not the outer loop. We can break out of the outer loop if there was a corresponding break statement within the immediate body of the outer loop. The continue statement behaves in a similar fashion in relation to inner and outer loops.