Write a program to input a string in uppercase and print the frequency of each character.
Example:
Input: COMPUTER HARDWARE
Output:
CHARACTERS FREQUENCY A 2 C 1 D 1 E 2 H 1 M 1 O 2 P 1 R 2 T 1 U 1 W 1
import java.io.*;
class Frequency {
String s;
int i, j, l, f;
void display() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string in upper case:");
s = br.readLine();
l = s.length();
System.out.println("CHARACTERS FREQUENCY");
for (i = 65; i <= 90; i++) { // ASCII values for 'A' to 'Z'
f = 0;
for (j = 0; j < l; j++) {
if (s.charAt(j) == i) {
f++;
}
}
if (f > 0) {
System.out.println((char)i + "\t\t" + f);
}
}
}
public static void main(String[] args) throws IOException {
Frequency freq = new Frequency();
freq.display();
}
}
Variable Table
| Variable | Type | Description |
|---|---|---|
s |
String |
To store the input string. |
i |
int |
Loop variable for ASCII values from 65 ('A') to 90 ('Z'). |
j |
int |
Loop variable for iterating through the string. |
l |
int |
To store the length of the input string. |
f |
int |
To store the frequency of each character. |
This program counts and prints the frequency of each character in the input string, considering only uppercase letters.
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.