简体   繁体   中英

nested for loops making square

I wanna make a square with numbers.Something like this:

1 2 3 4 
2 3 4 5 
3 4 5 6 

And i wrote a peace of code:

int a=input.nextInt();
for(int i=1; i<=a; i++){
    for (int k=1;k<=a;k++){
        int c=k+1;
        int g=k+2;
        System.out.println();
        System.out.print(k+" ");
        System.out.print(c+" ");
        System.out.print(g+" ");
    }
    System.out.println();

the result is:

1 2 3 4 
2 3 4 5 
3 4 5 6 

1 2 3 4 
2 3 4 5 
3 4 5 6 

So, where is the mistake?

You are printing a full square in the second loop. The first one is producing multiple squares.

Try this code:

   public static void main(String[] args) {
      //      int a=input.nextInt();
      int a = 4;

      for (int i = 1; i <= a; i++) {
         for (int k = 0; k < a; k++) {
            System.out.print(i + k);
            System.out.print(" ");
         }
         System.out.println();
      }
   }

If you just remove your first loop it will print only one square.

int a=input.nextInt();
//for(int i=1; i<=a; i++){  comment this one
  for (int k=1;k<=a;k++){
    int c=k+1;
    int g=k+2;
    System.out.println();
    System.out.print(k+" ");
    System.out.print(c+" ");
    System.out.print(g+" ");
 }
System.out.println();
//} and this

and square will only be printed if you give input as 3.

1 2 3 
2 3 4 
3 4 5 

for your square

    public static void main (String[] args) throws java.lang.Exception
{

int a=3;
//for(int i=1; i<=a; i++){
    for (int k=1;k<=a;k++){
    int c=k+1;
    int g=k+2;
    int e=k+3;//added
    System.out.println();
    System.out.print(k+" ");
    System.out.print(c+" ");
    System.out.print(g+" ");
     System.out.print(e+" ");//added
    }
System.out.println();
//}
}

output:

1 2 3 4 
2 3 4 5 
3 4 5 6

Because a single loop will do just fine in your case.

Considering you are taking number of rows as input

your loop should run from i=1 to i<=a.

you don't need to take another loop just print i,i+1,i+2,i+3 inside the loop.

Try This

public static void main(String[] args) {          
          int a = 4;
          for (int i = 1; i <= a-1; i++) {
             for (int j = 0; j < a; j++) {
                System.out.print(i + j);
                System.out.print(" ");
             }
             System.out.println();
          }
       }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM