Home / Programs / Write a Java program to count how many times a value appears in an array.
Programming Example

Write a Java program to count how many times a value appears in an array.

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

Information & Algorithm

Given Input:

Enter value to count: 10

Expected Output:

Occurrence count: 3

Program Code

import java.util.Scanner;

class CountOccurrences {
    public static void main(String[] args) {
        int[] arr = {10, 20, 10, 30, 10, 40};
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter value to count: ");
        int key = sc.nextInt();

        int count = 0;

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == key) {
                count++;
            }
        }

        System.out.println("Occurrence count: " + count);
    }
}

Explanation

The program checks every element of the array and increases the counter whenever the value matches.

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.