It was an interview question. I had to print the following using Java:
9
9 8 9
9 8 7 8 9
9 8 7 6 7 8 9
. . .
. . .
During the interview, I wrote the embarrassing part of the code, but nonetheless worked using an external loop, two internal ones (one for the decrementing sequence and one for the incremental sequence!) And tons of variables. One variable was the length of each line.
The interviewer asked me to rewrite it using
Note. After looking at the answers, I think that the interviewer did not really mean the second condition. Perhaps he just wanted me to simplify my code, and the second moment just burst out of his mouth.
So, later home, I came to this:
int rowCnt = 5;
for(int i = 1; i <= rowCnt; i++)
{
int val = 9;
int delta = -1;
int rowLen = i * 2 - 1;
for(int j = 1; j <= rowLen; j++)
{
System.out.print(val + " ");
val += delta;
if(j >= rowLen / 2) delta = 1;
}
System.out.println();
}
. delta, , . .
- . , .
?
, , , .
user1699872