Search code examples
javafor-loopnumbersline-breaks

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


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 + " ");
            }

        }

    }

Solution

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