Diamond
Completed
Read an odd n and print a diamond of stars whose middle row has n stars.
Input
One odd integer.
Output
n rows.
Example
Input
5
Output
* *** ***** *** *
Editor
Java
Hints
Loop i from -n/2 to n/2: |i| is the number of spaces.
Solution explanation
Using a symmetric loop variable makes the top and bottom halves come out of one loop.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int half = n / 2;
for (int i = -half; i <= half; i++) {
int stars = n - 2 * Math.abs(i);
StringBuilder row = new StringBuilder();
for (int s = 0; s < Math.abs(i); s++) {
row.append(' ');
}
for (int s = 0; s < stars; s++) {
row.append('*');
}
System.out.println(row);
}
}
}