I'd like to create a method that counts how many times a number is occurred in a 2D array. using for loop
-
1Show us what you got so far.dambros– dambros2016-04-02 15:23:54 +00:00Commented Apr 2, 2016 at 15:23
-
Welcome to Stack Overflow! Did you try to solve this yourself already? If so, where did you get stuck exactly? I general, people don't respond too well to "please make this code for me"-requests (which this looks like), but do respond well to "I tried this and now I'm stuck/confused, please help"-requests ;-)Martin Tournoij– Martin Tournoij2016-04-02 17:41:59 +00:00Commented Apr 2, 2016 at 17:41
Add a comment
|
2 Answers
2D arrays can be declared like int[][] matrix = new int[10][10]; If you need 2D array with different number of values in rows, than you have to create each row by yourself:
int [][] matrix = new int[10][];
matrix[0] = new int[10];
matrix[1] = new int[20];
//...
To iterate over matrix you need
for (int[] row : matrix) {
for (int value : row) {
sum += value;
}
}
3 Comments
Vikrant Kashyap
@Danis please see what he actually asks and what you try to answer ?
Çağrı Çetiner
For example i want to find which number is greater than any number in 2D arrays and for this, i create a this code : int [][] movie = { {4,6,2,5}, {7,9,4,8}, {6,9,3,7} }; int count =0; for(int i = 0; i<movie.length;i++) for(int j = 0; j<movie[i].length;j++) if(rate == movie[i][j]){ count++; } System.out.println(count); }
Vikrant Kashyap
@ÇağrıÇetiner You have asked about counting the occurrences of a number within a 2-D Array. not mentioning any greater or less than context in your question. So my answer is as per your question .
//method to count your number of Occurrences in Your 2-D Array.
private int getAllOccurence(int [] arr, int yourNumberToSearch){
int count = 0;
for (int[] row : arr) { //loop will able to get all Rows
for (int value : row) { //loop enables you to get each values of each Row.
// This if Statement will check wheather Your Number exists in array or not
if(value == yourNumberToSearch)
count++; //count increase each times by one If Number exists in a array.
}
}
return count;
}
Here You may try this. You will get Your Answer.
4 Comments
Çağrı Çetiner
i cant understand that part : for (int[] row : arr) { for (int value : row) {
Vikrant Kashyap
its a double dimensional array so First loop will get your all rows. And nested loop (for which is inside a for loop) will get you each element of your row.
Vikrant Kashyap
@ÇağrıÇetiner Now I am edit my answer and add comment to abbreviate my answer which makes you a little more understandable
Vikrant Kashyap
@ÇağrıÇetiner If you get your answer then accept it as a verified. This answer might helpful for others