Try this:
void display()
{
int i=0,k;
for(i=1;i<=5;i++)
{
for(k=1;k<=5;k++)
{
if (k < i ) {
System.out.print(i);
} else {
System.out.print(k);
}
}
System.out.println();
}
}
Your pattern is dependant on the line number i
:
- Line n should print n, n times
- fill the remainder of the line with incresing integers starting with n up to the length of the line/max number of lines.
You could generalize it to make the pattern more readable:
void display(int dimension)
{
int lineNumber = 0, linePosition = 0;
int numberOfLines = dimension, numberOfCharactersPerLine = dimension;
for(lineNumber =1;lineNumber<=numberOfLines ; lineNumber++)
{
for(linePosition = 1;linePosition <= numberOfCharactersPerLine ;linePosition++)
{
if ( linePosition < lineNumber ) {
System.out.print(lineNumber);
} else {
System.out.print(linePosition);
}
}
System.out.println();
}
}
Here we see the instructions with explicitly named variables. If the linePosition
(the current character in the line we are deciding to print) is less than the line number we should print the line number, otherwise print the character position.
This is probably better imagined by picturing it as a two dimensional matrix with coordinates and you are filling it in based on those coordinates.