Java Online Compiler
Example: Array Element Frequency using Nested Loops in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Array Element Frequency using Nested Loops import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Initialize the array int[] arr = {10, 20, 20, 10, 10, 30, 40, 50, 20, 40}; int n = arr.length; // Step 2: Create a boolean array to keep track of visited elements // This helps avoid recounting elements that have already been processed. boolean[] visited = new boolean[n]; // Step 3: Iterate through the array for (int i = 0; i < n; i++) { // Step 3a: Skip if the element at index 'i' has already been visited if (visited[i]) { continue; } // Step 3b: Initialize count for the current element int count = 1; // Step 3c: Iterate through the rest of the array (elements after 'i') // to find duplicates of arr[i] for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { count++; visited[j] = true; // Mark duplicate as visited to avoid recounting } } // Step 3d: Print the frequency of the current unique element System.out.println(arr[i] + ": " + count + " times"); } } }
Output
Clear
ADVERTISEMENTS