Home / Programs / Write a program to input a string in uppercase and print the frequency of each character.
Programming Example

Write a program to input a string in uppercase and print the frequency of each character.

👁 181 Views
💻 Practical Program
📘 Step by Step Learning
Study this program carefully to understand the logic, output, and explanation in a structured way.

Information & Algorithm

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

Program Code

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();
    }
}

Explanation

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.

How to learn from this program

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.