Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I design an int loop that starts with 1 and ends with 0 (1,2,3,4,5,6,7,8,9,0)

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);
   }
}
like image 596
JP Wile Avatar asked Dec 09 '10 23:12

JP Wile


People also ask

How do nested for loops work?

A nested loop is a loop within a loop, an inner loop within the body of an outer one. How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes.


2 Answers

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);
}
like image 78
Adam Avatar answered Oct 09 '22 05:10

Adam


You want the mod operator (%).

10 % 10 = 0
11 % 10 = 1

It calculates the remainder after division.

like image 24
Noon Silk Avatar answered Oct 09 '22 07:10

Noon Silk