KZukic
KZukic

Reputation: 25

Generate a number-pattern in Java beginning with different numbers

I am preparing for my exam from programming. And I am stuck on this task, I understand logic of patterns ( at least I think so ) but I can't figure out how to solve this.

Output for input a = 6 needs to be like :

012345
123456
234567
345678
456789
567890

Output for input a = 3 needs to be like :

012
123
234

Output for input a = 4 needs to be like :

0123
1234
2345
3456

But I'm getting this :

0 1 2 3 4 5 
1 2 3 4 5 
2 3 4 5 
3 4 5 
4 5 
5 

Here's my code:

for (int i = 0; i <= a; i++) {

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

    System.out.println();
}

Upvotes: 2

Views: 182

Answers (2)

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 29068

You need to make these changes to get the required output:

  • Termination conditions of the outer for loop should be i < a;

  • Termination conditions of the inner for loop should be j < a + i;

  • The number you're printing should be not j but j % 10 to satisfy the data sample you've provided (for input a=6 it prints 0 as the last number on the very last line instead of 10, that means we need not j, but only its rightmost digit which is the remainder of division by 10).

That's how it can be fixed:

public static void printNumbers(int a) {
    for (int i = 0; i < a; i++) {
        for (int j = i; j < a + i; j++) {
            System.out.print(j % 10 + " ");
        }
        System.out.println();
    }
}

Upvotes: 2

Gurkirat Singh Guliani
Gurkirat Singh Guliani

Reputation: 1015

Observations: Since it is a 2 dimensional output, we will need 2 loops ( one inside the other ).

Also, the starting point for each line is the value from which the last line starts +1 .

If the value crosses 10, then we will keep the unit digit value only ( like in the last line). ( therefore we use modulus operator % that helps to extract the unit digit)

Code :

class Main {
    public static void main(String[] args) {
        int n = 6;
        pattern(n);
    }

    private static void pattern(int n) {
        int k = 0;
        for (int i = 0; i < n; i++) {
            for (int j = k; j < k + n; j++) {
                System.out.print(j % 10);
            }
            k = i + 1;
            System.out.println();
        }
    }

}

and the answer is :

012345
123456
234567
345678
456789
567890

Upvotes: 1

Related Questions