Search code examples
javaalgorithmfor-loopnumbers

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();
}

Solution

  • 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();
        }
    }