Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 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 Answer

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();
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...