I'm attempting to solve some Java questions and I came across a question that asked me to print out a diamond of size n
.
Since I got stumped on this question, I decided to look up other's solutions to get an idea as to how I could tackle this problem.
A diamond of size 2 should look like this by the way.
##*##
#***#
##*##
However, one part of the code really stumped me out and that is how does the #
get printed out in that manner.
Here is what I found for the top left bit of the diamond, basically this bit:
##
#
Here is the code for that:
public static void printDiamond(int k){
for(int i=1; i <= k; i ) {
for(int j = i; j <= k; j ) {
System.out.print("#");
}
System.out.println("");
}
}
and the output when k = 5:
#####
####
###
##
#
From my understanding, int j
is looping upwards since it's declared as i
which also loops upwards until it reaches k
.
Shouldn't that print out 1,2,3,4,5 diamonds instead since the loop goes from 0 to k, which is 5?
I was expecting the output to be like:
#
##
###
####
#####
Can someone explain how does the code snippet I attached returns the output from top to bottom?
CodePudding user response:
A simple pen and paper exercise will uncover the details.
for(int i = 1; i <= k; i ) {
for(int j = i; j <= k; j ) {
...
}
}
When i = 1
, j
runs from 1
to k
. So, it will print the star k
times. That is how you get k
stars in row 1.
When i = 2
, j
runs from 2
to k
. So, it will print the star k - 1
times. That is how you get k - 1
stars in row 2.
And so on...
When i = k
, j
runs from k
to k
which is one time and hence you get only one star in the last row.
CodePudding user response:
Initial value of j
is set to incrementing i
and the inner loop is limited with the fixed value k
. That is, the first run prints #
from 1 to 5 (5 times), the second run prints from 2 to 5, etc. and the number of prints is decreasing.
To print the lower part in increasing way, the limit should be set to i
: for (int j = 1; j <= i; j 0) System.out.print("#")
.
Also, the inner loops may be replaced with the method String::repeat
available since Java 11:
public static void diamond(int k) {
// upper part, decreasing # increasing *
for (int i = 1; i <= k; i ) {
System.out.println("#".repeat(k - i) "*".repeat(2 * i - 1) "#".repeat(k - i));
}
// lower part, decreasing * increasing #
for (int i = 1; i < k; i ) {
System.out.println("#".repeat(i) "*".repeat(2 * (k - i) - 1) "#".repeat(i));
}
}