In: Computer Science
in java language
Write a method called findNums that takes a two-dimension array of integers and an int as parameters and returns the number of times the integer parameter appears in the array. For example, if the array (as created by the program below) is
10 45 3 8
2 42
3 21 44
And the integer parameter is 3, the value returned would be 2 (the number 3 appears two times in the array)
public class Question2 {
public static void main(String args[]){
int arr[][] = {{10, 45, 3, 8}, {2, 42}, {3, 21, 44}};
System.out.println(“The number time 3 appears is “+findNums(arr,3));
} //main
Below is the complete Java code. If you face any difficulty while understanding the code, please let me know in the comments.
Code:
public class Question2 {
// Method finfNums
public static int findNums(int arr[][], int target) {
// To store the total count of target
int count = 0;
// Calculate total number of rows in the 2D array
int m = arr.length;
for(int i = 0 ; i < m ; i++) {
// Calculate total no. of items in the ith row
int n = arr[i].length;
for(int j = 0 ; j < n ;j++)
if (arr[i][j] == target)
count++;
}
return count;
}
public static void main(String[] args) {
int arr[][] = {
{10, 45, 3, 8},
{2, 42},
{3, 21, 44}
};
System.out.println("The number of time 3 appears is "
+ findNums(arr,3));
}
}
Screenshot:
Output: