Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 .
So to output for a=6 needs to be like :

012345
123456
234567
345678
456789
567890

So to output for a=3 needs to be like :

012
123
234

So to output for a=4 needs to be like :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

0123
1234
2345
3456

But I get 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();
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading