Enter value to count: 10
Occurrence count: 3
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);
}
}
The program checks every element of the array and increases the counter whenever the value matches.
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.