Java Program to count the occurrence of a number
Program
import java.util.*;
public class CountOccurence
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of an array:");
int size = sc.nextInt();
int arr[] = new int[size];
System.out.println("Enter the array elements:");
for(int i = 0; i < size ; i++)
arr[i] = sc.nextInt();
System.out.println("Enter the item to check:");
int item = sc.nextInt();
int count = 0;
for(int i = 0; i < size ;i++)
if(arr[i] == item)
count++;
if(count > 0)
System.out.println("Element found for " + count + " times");
else
System.out.println("Element not found");
}
}
This Java program counts the occurrences of a specific number in an array provided by the user.
-
User Input for Array Size:
- The program prompts the user to input the size of the array.
- The size is stored in the variable
size
.
-
Array Initialization:
- An integer array
arr
of sizesize
is created.
- An integer array
-
User Input for Array Elements:
- The program asks the user to input the elements of the array.
- A
for
loop iterates from0
tosize - 1
, and each element is stored in the array.
-
User Input for Item to Check:
- The program prompts the user to input the number they want to check for in the array.
- This value is stored in the variable
item
.
-
Count Occurrences:
- A variable
count
is initialized to0
. - A
for
loop iterates through the array, and for each element that matchesitem
,count
is incremented. - The program uses a
for
loop to traverse the array and compare elements. - The program tracks how many times a specific number appears in the array by incrementing the
count
variable when a match is found.
- A variable
-
Display Result using Conditional Statements:
- An
if-else
block is used to determine whether theitem
exists in the array and display the appropriate message. - If
count > 0
, the program prints the number of timesitem
was found in the array. - If
count == 0
, it prints that the element was not found.
- An
Output 1:
Enter the size of an array:
10
Enter the array elements:
12
34
5656
23
78
12
45
12
678
32
Enter the item to check:
12
Element found for 3 times
Output 2:
Enter the size of an array:
6
Enter the array elements:
11
21
31
41
51
61
Enter the item to check:
71
Element not found