java find all instances of int in arry

Solutions on MaxInterview for java find all instances of int in arry by the best coders in the world

showing results for - "java find all instances of int in arry"
Erica
17 Nov 2017
1// Java program to count occurrences 
2// of an element 
3
4class Main 
5{ 
6	// Returns number of times x occurs in arr[0..n-1] 
7	static int countOccurrences(int arr[], int n, int x) 
8	{ 
9		int res = 0; 
10		for (int i=0; i<n; i++) 
11			if (x == arr[i]) 
12			res++; 
13		return res; 
14	} 
15	
16	public static void main(String args[]) 
17	{ 
18		int arr[] = {1, 2, 2, 2, 2, 3, 4, 7 ,8 ,8 }; 
19		int n = arr.length; 
20		int x = 2; 
21		System.out.println(countOccurrences(arr, n, x)); 
22	} 
23} 
24