Java: Draw a diamond of stars

Nested loops draw shapes: one loop for the rows, inner loops for each row's characters.

What to build

A program that draws a diamond n rows tall in its top half.

Requirements

  • Read n. Print a diamond whose widest row has 2n - 1 stars: rows 1 to n grow by two stars, and rows n - 1 down to 1 shrink again.
  • Each row starts with enough spaces to centre it, and has no spaces after its stars.
  • If n is 0, print empty.

Input

One whole number n.

Output

2n - 1 lines, or empty.

Constraints

0 ≤ n ≤ 30.

Example

Input:

3

Output:

  *
 ***
*****
 ***
  *

Why it works

The outer loops choose the row and the inner loops print the spaces and the stars for it; working out n - i and 2i - 1 for row i is the whole trick.

Examples

Example 1 · Input
3
Expected output
  *
 ***
*****
 ***
  *
Example 2 · Input
1
Expected output
*

Hints

Hint 1

Row i of the top half (i from 1 to n) has n - i spaces and 2i - 1 stars.

Hint 2

The bottom half is the top half without its middle row, in reverse order.

Solution

Show one correct solution (try it yourself first)
import java.util.Scanner;

public class Main {
    static void row(int n, int i) {
        StringBuilder sb = new StringBuilder();
        for (int s = 0; s < n - i; s++) sb.append(' ');
        for (int s = 0; s < 2 * i - 1; s++) sb.append('*');
        System.out.println(sb);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        if (n == 0) {
            System.out.println("empty");
            return;
        }
        for (int i = 1; i <= n; i++) row(n, i);
        for (int i = n - 1; i >= 1; i--) row(n, i);
    }
}

Lesson: Decisions and loops →