How to arrange printed numbers using loops in processing? i.e. x and y axis in 10's up to a 100

Viewed 84

Ok, I know how to print the number up to whatever number but I am having trouble rearranging them.

This is the format I want..

1   2   3   4   5   6   7   8   9   10

11  12  13  14  15  16  17  18  19  20


21  22  23... 

all the way to 100. so, a 10 x 10 grid format.

This is the code I used:

size(500,500);
int x, y;
x= 30;
y= 30;

for(int i=1; i<=100; i++){
    text(i, x, y);
    x+=30;
}

however, it counts to a 100 in a straight line, and I'm not sure how to make 11 appear on the second line.

I have tried if statements, but the result is limited and requires numerous if statements to carry out the function all the way to 100. what do I do and how can the code be more efficient?

2 Answers

When the counter is a multiple of 10, increase the y coordinate and move the x coordinate back to the start of the line.

for(int i=1; i<=100; i++){
    text(i, x, y);
    x+=30;
    if(i % 10 == 0){
       x=30; 
       y += 30;
    }
}

If we want to completely eliminate 'IF' statements, then we can rewrite this code as follows.

for(int i=0; i<=99; i++) {
    x = 30 + (i % 10) * 30;
    y = 30 + (i/10) * 30;
    text(i+1, x, y);
}

Code explanation :

  1. In this code, the loop is started from 0 and ends at 99 and for printing, we have used i+1 so it will print 1 to 100 as expected.
  2. For calculation purpose, we have used the value of i and for printing, we have used i+1. So keep in mind that i will be always one less than current number in loop.
  3. x is increasing by 30 with each i and get resets to 30 when the number is again 11 or 21... and so on. So if we calculate x is in multiple of 30 with the remainder of 10. And when number is 1 it should be initialized to 30. So the formula will be...
    x = 30 + (i % 10) * 30;
  4. y is increasing with every 10 numbers as 11 is needs to be printed on the next line. So y is increasing in multiple of 30 with the division of 10. So formula will be...
    y = 30 + (i/10) * 30;
Related