Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fill a two demensional array with values from 1 to 25?

I am stuck one one task and I need some help. This is the code I already wrote:

int [][] arr = new int [5][5];
        
        for(int val = 1; val<=5;val++){
            for(int i = 0; i < 5; i++){
                for(int j = 0; j < 5; j++){
                    arr[i][j] =  val;
                }    
            }
        }
        for(int k = 0; k < 5; k++){
            for(int l = 0; l < 5; l++){
                System.out.print(arr[k][l] + "   ");
            }
            System.out.println();
        }

The out put is only:

5   5   5   5   5   
5   5   5   5   5   
5   5   5   5   5   
5   5   5   5   5   
5   5   5   5   5

The out put should look ike this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1  2  3  4  5
6  7  8  9  10
...and so on 25

>Solution :

You dont need 3 loops, 2 are enough to populate the array.

public class MyClass {
    public static void main(String args[]) {
        int [][] arr = new int [5][5];
        for(int i = 0; i < 5; i++){
            for(int j = 0; j < 5; j++){
                arr[i][j] =  (i * 5) + (j + 1);
            }    
        }
        for(int k = 0; k < 5; k++){
            for(int l = 0; l < 5; l++){
                System.out.print(arr[k][l] + "   ");
            }
            System.out.println();
        }
    }
}

prints

1    2    3    4    5   
6    7    8    9    10   
11   12   13   14   15   
16   17   18   19   20   
21   22   23   24   25   
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading