Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

java - Printing Concentric Squares of Numbers

I have been practicing patterns until I reached this pattern. It says print concentric squares of numbers with max layer as NxN and Min layer 1x1

   For instance, for input N=3 the desired 
    o/p should be 

   33333
   32223
   32123
   32223
   33333

I tried like

     for(int i=1;i<=2*N-1;i++)   
         { 
              for(int j=1;j<=2*N-1;j++) 
            {
    if(i==1 || i==N) --for max n min layer
             System.out.print(N);
else if(j!=1 || j!=N) --for col not as max n min and rows between max n min
             System.out.print(N-1);
             else 
                 System.out.print(N);
               }}

I know that its wrong but I want it to be solved in a conventional way as above sample meaning step by step.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this below code and you can change the below code according to your requirement

Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int size = 2*n-1;
    int start=0;
    int end=size-1;
    int [][]a = new int[size][size];
while(n!=0) {
    for (int i=start;i<=end;i++) {
        for (int j=start;j<=end;j++) {
            if((i==start)||(j==start)||(i==end)||(j==end))
                a[i][j] = n;
        }
    }
    start++;
    end--;
    n--;
}
    for (int i=0;i<size;i++) {
        for (int j=0;j<size;j++) {
            System.out.print(a[i][j]+" ");
        }
        System.out.println();
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...