Programming Example
Write a Java program to count how many times a value appears in an array.
Study this program carefully to understand the logic, output, and explanation in a structured way.
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 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.