Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print 10 Numbers Per Line

Tags:

java

I am trying to print a loop of numbers, with 10 numbers per line. Here is what I have done so far:

for(int i = 100; i < 200; i++) {

    System.out.print(i++);

    System.out.print(" ");

}

The output I get is

100 101 102 103 104 105 106 107 108 109 110 111....

I have tried creating another loop with variable j < 11 and then putting System.out.println() however that just prints 10 returns then the next number. I am trying to accomplish this output:

100 101 102 103 104 105 106 107 108 109
110 111 112 113...
like image 704
Sameer A. Avatar asked Dec 13 '25 23:12

Sameer A.


2 Answers

try ternary operator ?:

If your input is fixed from 100 to 200 then you can try:

for(int i = 100; i < 200; i++) {    
     System.out.print(i+ ((i%10==9) ? "\n" : " "));
}

will output:

100 101 102 103 104 105 106 107 108 109
110 111 112 113 114 115 116 117 118 119
120 121 122 123 124 125 126 127 128 129
130 131 132 133 134 135 136 137 138 139
...

Here is Demo on IDEONE

But if you input is not fixed then try ie 105 to 200:

int start = 105;
for(int i = start; i < 200; i++) {
  System.out.print(i+ ((i-(start-1))%10==0 ? "\n" : " "));
}

will output:

105 106 107 108 109 110 111 112 113 114
115 116 117 118 119 120 121 122 123 124
125 126 127 128 129 130 131 132 133 134
...

Here is demo

like image 57
Zaheer Ahmed Avatar answered Dec 15 '25 12:12

Zaheer Ahmed


for(int i = 100; i < 200; i++) {
    if(i%10==0){
        System.out.println();
    }
    System.out.print(i+" ");
}
like image 40
Pratik Roy Avatar answered Dec 15 '25 13:12

Pratik Roy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!