Home > database >  Line break after every 20th number in Java (for-loop)
Line break after every 20th number in Java (for-loop)

Time:11-01

I am trying to write a program, which shows numbers 1 to 100. I would like to have a line break after every 20th number. I have tried using a counterloop, which resets itself after every 20th number, but the program runs infinite. How do I fix this?

public class zahlen1_bis_100 {
    public static void main(String[] args) {


        for (int x = 1; x <= 100; x  ) {
            for (int counter = 1;counter <= 20; counter  ) {

                    if (counter == 20) {

                        System.out.println();
                        counter = 1;
                    }
                }
             System.out.print(x   " ");
            }

        }

    }

CodePudding user response:

There is no point in using an inner loop. Instead of that, you can implement a if statement to break into next line.

Logic => if the number is a multiple of 20, then break into next line.

Implementation =>

public static void main(String[] args) {


    for (int x = 1; x <= 100; x  ) {
        System.out.print(x   " ");
        if(x ==0){
            System.out.println();
        }
    }

Output =>

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 

CodePudding user response:

            for (int x = 1; x <= 100; x  ) {
                 System.out.print(x   
                         (x % 20 == 0 ? "\n" : " ")
                             );
                 
                }

            }

Inside the print, it prints x and then checks if the x is a multiple of 20 to print a new line; Otherwise prints a space. It's in Ternary Operator format, but could also be written in normal if block format:

            for (int x = 1; x <= 100; x  ) {
                
                System.out.print(x);
                
                if (x % 20 == 0) 
                    System.out.print(" ");
                else
                    System.out.println();
                 
                }

            }

CodePudding user response:

Thank you all for your help! I wanted to create a "unified" look of the output , so I ended up with the following code:

public class zahlen1_bis_100 {
    public static void main(String[] args) {


        for (int x = 1; x <= 100; x  ) {


            if (x < 10) {
                System.out.print(x   "  ");

            } else {
                System.out.print(x   " ");
            }
            if (x % 20 ==0) {
                System.out.println();
            }

        }


    }
}
[Result][1]


  [1]: https://i.stack.imgur.com/66tXZ.png
  • Related