打印数字的同心平方 [英] Printing Concentric Squares of Numbers

查看:96
本文介绍了打印数字的同心平方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在练习模式,直到达到这种模式为止.它表示以最大层为 NxN 和最小层为 1x1

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

我尝试过

     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.

推荐答案

尝试以下代码,您可以根据需要更改以下代码

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

这篇关于打印数字的同心平方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆