The following block should generate the series as you described it.
int numberOfLines = 4;
int numberOfDigitsPerLine = 5;
for (int i=1; i<numberOfLines+1; i++){
for(int j=1; j<=numberOfDigitsPerLine; j++) {
if(j>=i) {
System.out.print(j);
} else {
System.out.print(i);
}
}
System.out.println();
}
Change numberOfLines
and numberOfDigitsPerLine
as necessary.
Elaboration:
First you must analyze the series, by the looks of it the first number starts with 1 and goes onward for 5 digits, the second line goes along 5 digits as well up to 5 as previously but it replaces the first digit with 2.
Moving down the numbers we can see a pattern of which the N-th number will have N amount of N digits followed by consecutive digits up to the number 5.
So in my code above I chose max N to be 4 as you described it, and the numbers go up to 5, these are represented by the variables numberOfLines
and numberOfDigitsPerLine
respectively.
The block itself checks what is N at that point (in my block it is represented by i
) and then proceeds to go towards the max number 5, this is done within the j
for loop. If j is larger or equal to N then we print j, otherwise we haven’t finished printing all of the N’s yet so we print N instead.
1
solved I have to print a series using for loop