Search code examples
loopsprocessing

Use loop to print values as requested


print out below table in console using a nested loop

Hi question how do I print out above in console from processing.

    int result;
    for (int i=100 ; i < = 10; i + = 10) { 
       result = 100; 
       for (int k=2; k <= 10; k++) { 
          result-=10 ; 
       } print(result);
        println();
    }
  • My thought is it looks like a 10*10 table thus both i and k is < = 10.
  • And other thought is when i is odd i starts from 100 and -=10 (i > = 10) when i is even(line 2,4,6...) i start from 10 and +=10 ( i<=100) Then I got the printed table.

But I am stuck how to achieve this in code if my logic is correct as mentioned above.


Solution

  • You can do it with 2 nested loops:

    for (int i=0; i<10; ++i) { 
         for (int j=0; j<10; ++j) {
            print(str(i%2 == 0 ? (10-j)*10 : (j+1)*10) + " ");
         }
         println();
    }
    

    Or one single loop:

    for (int i=0; i<100; ++i) { 
         int j = i%10;
         print(str((i/10)%2 == 0 ? (10-j)*10 : (j+1)*10) + " ");
         if (i % 10 == 9) {
           println();
         }
    }
    

    Output:

    100 90 80 70 60 50 40 30 20 10 
    10 20 30 40 50 60 70 80 90 100 
    100 90 80 70 60 50 40 30 20 10 
    10 20 30 40 50 60 70 80 90 100 
    100 90 80 70 60 50 40 30 20 10 
    10 20 30 40 50 60 70 80 90 100 
    100 90 80 70 60 50 40 30 20 10 
    10 20 30 40 50 60 70 80 90 100 
    100 90 80 70 60 50 40 30 20 10 
    10 20 30 40 50 60 70 80 90 100