Number Pattern Printing in Java

Aishu :

I'm newbie to programming. So as an exercise, I'm trying to print a number pattern like below

   4
  34 
 234 
1234 

I tried the below code

public static void main(String[] args) {
        // TODO Auto-generated method stub

        int n =4;
        for (int i = 1; i <= n; i++) {

            for (int j = i; j <= n; j++) {
                System.out.print(" ");
            }

            int num = 4;

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

        }

    }

but it is printing in this way.

    4
   43
  432
 4321

I think, I have to decrement the value before printing. Please correct me if i'm wrong. But I'm stuck here. Can anyone please help me?

Roland Illig :

This is the pattern you want to get:

   4
  34
 234
1234

When you describe the pattern in words, it could look like this:

  • line 1 has 3 spaces, and then the digit 4
  • line 2 has 2 spaces, and then the digits 3 and 4
  • line 3 has 1 space, and then the digits 2 to 4
  • line 4 has 0 spaces, and then the digits 1 to 4

There is already some kind of pattern here. The last two lines look remarkably similar. Let's see whether the first two lines can be brought into the same form:

  • line 1 has 3 space(s), and then the digits 4 to 4
  • line 2 has 2 space(s), and then the digits 3 to 4
  • line 3 has 1 space(s), and then the digits 2 to 4
  • line 4 has 0 space(s), and then the digits 1 to 4

Now that looks good. The next step is to change the wording to depend on the given line:

  • line i has (4 - i) space(s), and then the digits (4 - i + 1) to 4

I took care not to say 5 instead of the 4 + 1, so that the 4 is still visible. Let's give this 4 another name:

  • line i has (max - i) space(s), and then the digits (max - i + 1) to max

Now you should be able to translate this instruction into Java code.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143524&siteId=1