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();
}
}
CodePudding user response:
You need to make these changes to get the required output:
Termination conditions of the outer
for
loop should bei < a
;Termination conditions of the inner
for
loop should bej < a i
;The number you're printing should be not
j
butj % 10
to satisfy the data sample you've provided (for inputa=6
it prints0
as 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();
}
}
CodePudding user response:
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