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 :
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
forloop should bei < a; -
Termination conditions of the inner
forloop should bej < a + i; -
The number you’re printing should be not
jbutj % 10to satisfy the data sample you’ve provided (for inputa=6it prints0as the last number on the very last line instead of10, that means we need notj, but only its rightmost digit which is the remainder of division by10).
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();
}
}