user3660378
user3660378

Reputation:

java-Printing Reversed Triangle containing numbers 9-0

Hello guys i need your help here is my code

public class act_numTria {
  public static void main(String[] args) {
    int z = 9;
    for(int x = 1; x <= 4; x++) {
      for(int y = 4; y >= x; y--) {
        System.out.print(z);
        z--;
      }
      System.out.print("\n");
    }
  }
}

the output is:

9876
543
21
0

but it should be like this

6789
345
12
0

Upvotes: 1

Views: 458

Answers (2)

Sanjeev
Sanjeev

Reputation: 9946

Here is a modified code of yours .. you just need to accumulate your digits and then reverse it:

 public class act_numTria {

    public static void main(String[] args) {
        int z = 9;
        for (int x = 1; x <= 4; x++) {
            StringBuilder sb = new StringBuilder();
            for (int y = 4; y >= x; y--) {
                sb.append(z--);
            }
            System.out.print(sb.reverse().toString() + "\n");
        }

    }
}

Here is another solution to your problem:

public class act_numTria {

        public static void main(String[] args) {
            int start = 6;
            int diff = 3;
            for (int z = start; diff>=0; z=start) {
                for(int i=z;i<=start+diff;i++) {
                    System.out.print(i);
                }
                System.out.println();
                start-=diff;
                diff--;
            }

        }
    }

Upvotes: 0

aksh1t
aksh1t

Reputation: 5448

If you don't want to involve any string operations, you can do this...

public class act_numTria {
   public static void main(String[] args) {
      int z = 9;
      for(int x=1;x<=4;x++){
         for(int y=4;y>=x;y--){
            System.out.print(z-y+1);
         }
         z = z - (4 - x);
         System.out.print("\n");
      }
   }
}

Upvotes: 1

Related Questions