11

My problem is to use nested for loops in order to create this output:

         |         |         |         |         |         |
123456789012345678901234567890123456789012345678901234567890

I can't figure out the best way to replace the int 10 with 0. I've tried a few ways, but they are gimmicky, and don't seem right to me. I hope my problem is apparent, it's kind of hard to explain. Can someone point me in the right direction?

I've achieved the correct output, but something tells me that there is a better way to go about this. Here's my code:

int k = 0;  
for (int i=1; i<=6; i++){
   System.out.print("         |");
}
System.out.println();
for (int m=0; m<6; m++){
   for (int j=1; j<10; j++){
      System.out.print(j);
   }
   System.out.print(k);
}

Great! Modulo was the answer I was looking for. I feel much more comfortable with this:

for (int i=1;i<=6;i++){
   System.out.print("         |");
}
System.out.println();
for (int m=0;m<6;m++){
   for (int j=1;j<=10;j++){
      System.out.print(j % 10);
   }
}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
JP Wile
  • 156
  • 3
  • 11

8 Answers8

11

Use the modulo operator %. It gives you the remainder. Therefore starting the loop at 1, when 1 is divided by 10 the remainder is 1. When 2 is divided by 10 the remainder is 2, etc.. When 10 is divided by 10 the output is 0.

for(int i = 1; i <= 10; i ++) {
      System.out.println(i % 10);
}
Adam
  • 43,763
  • 16
  • 104
  • 144
10

You want the mod operator (%).

10 % 10 = 0
11 % 10 = 1

It calculates the remainder after division.

Noon Silk
  • 54,084
  • 6
  • 88
  • 105
8

Why can't you just generate this:

012345678901234567890123456789012345678901234567890123456789

And then take the character off the front and stick it on the end?

Anon.
  • 58,739
  • 8
  • 81
  • 86
3

There are many ways. The simplest is this, probably:

for (int i = 1; i <= 10; i++) {
   System.out.println(i % 10);
}

If you have 2 loops, then you can use this fact:

for (int i = 0; i < 5; i++) {
   for (int j = 1; j <= 9; j++) {
       System.out.print(j);
   }
   System.out.print(0);
}
Roman
  • 64,384
  • 92
  • 238
  • 332
2

If this represents a kind of pattern, then while not simply define the pattern and then output the result to the screen (or do whatever you want), it is:

printPattern("         |", 6);
printPattern("1234567890", 6);

public void printPattern(string pattern, int max)
{   
    int i = 0; 
    while (++i <= max)
        System.out.print(pattern);
    System.out.println();
}
ArBR
  • 4,032
  • 2
  • 23
  • 29
0

You could try using modulo:

i = i % 10
Conner
  • 30,144
  • 8
  • 52
  • 73
Matthieu
  • 16,103
  • 10
  • 59
  • 86
0
for (int i=1; i<100; i++)
    System.out.println(i%10);
John
  • 660
  • 10
  • 26
0

Here's a non-modulo solution:

$x = 1;
while(1){
  if($x>9){
     $x=0;
  }
print $x;
$x++;
}

Yea, yea, I know it's cheap. It'll work though. ;)

Satanicpuppy
  • 1,569
  • 8
  • 11