Java Online Compiler
Example: CharacterFrequencyUsingNestedLoops in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// CharacterFrequencyUsingNestedLoops public class Main { public static void main(String[] args) { String inputString = "programming"; // Step 1: Convert string to a character array to allow marking char[] stringChars = inputString.toCharArray(); int n = stringChars.length; System.out.println("Character frequencies (using nested loops):"); // Step 2: Outer loop to iterate through each character for (int i = 0; i < n; i++) { // Skip character if it has already been counted (marked as 0) if (stringChars[i] == 0) { continue; } int count = 1; // Current character counts itself // Step 3: Inner loop to compare with subsequent characters for (int j = i + 1; j < n; j++) { if (stringChars[i] == stringChars[j]) { count++; // Step 4: Mark the duplicate character to avoid recounting stringChars[j] = 0; } } // Step 5: Print frequency if character was not marked System.out.println(stringChars[i] + ": " + count); } } }
Output
Clear
ADVERTISEMENTS