Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to declare, initialize and print 2D array with different sizes for second dimensions in Java

1 Answer

0 votes
public class MyClass {
    public static void main(String args[]) {
        int Arr2D[][] = new int[5][];    
         
        Arr2D[0] = new int[1];    
        Arr2D[1] = new int[2];    
        Arr2D[2] = new int[3];    
        Arr2D[3] = new int[4];    
        Arr2D[4] = new int[5];   
         
        int n = 0;    
         
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < i + 1; j++) {      
                Arr2D[i][j] = n++;      
            }    
        }
        
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < i + 1; j++) {      
                System.out.printf("%3d", Arr2D[i][j]);      
            }  
            System.out.println();    
        }
    }
}



/*
run:

  0
  1  2
  3  4  5
  6  7  8  9
 10 11 12 13 14

*/

 



answered May 29, 2019 by avibootz
...