0

I'd like to create a method that counts how many times a number is occurred in a 2D array. using for loop

2
  • 1
    Show us what you got so far. Commented 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 ;-) Commented Apr 2, 2016 at 17:41

2 Answers 2

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

@Danis please see what he actually asks and what you try to answer ?
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); }
@Ç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 .
0
   //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

i cant understand that part : for (int[] row : arr) { for (int value : row) {
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.
@ÇağrıÇetiner Now I am edit my answer and add comment to abbreviate my answer which makes you a little more understandable
@ÇağrıÇetiner If you get your answer then accept it as a verified. This answer might helpful for others

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.