Search code examples
javafor-loopnestednested-loopscounting

For Loop pattern from 654321,54321.. to 1


Using Java,

I am trying to use nested for loops to make a chart that prints out 654321 to 1,

Example,

654321

54321

4321

321

21

1

The following code prints out a close enough example but instead of decreasing from the front decrease from the back,

654321

65432

6543

654

65

6

It is sort of doing what I want put not exactly, how would you make it count down from the beginning?

public class test_for_loops{

   public static void main (String [] args){
      int lines = 6;
      for (int i = 1; i <= lines; i++){
       for (int j = lines; j >= i; j--){
         System.out.print (j + " ");
         }   
      System.out.println();
    }
   }
}

Solution

  • Try this :

    int lines = 6;
    
    for (int i = 1; i <= lines; i++){
    
        for (int j = lines - i + 1; j >= 1; j--){
    
            System.out.print (j + " ");
        }
    
        System.out.println();
    }
    

    Output:

    6 5 4 3 2 1 
    5 4 3 2 1 
    4 3 2 1 
    3 2 1 
    2 1 
    1