C: A diamond of stars

Print a diamond shape made of stars.

What to build

A pattern that needs loops inside a loop.

Requirements

  • Read an odd number n.
  • Print a diamond that is n characters across at its widest and n lines tall.
  • Do not print spaces after the last star of a line.

Input

One odd whole number.

Output

n lines.

Constraints

n is odd, from 1 to 21.

Example

Input:

3

Output:

 *
***
 *

Why it works

Each row needs a known number of spaces and of stars. Working these out from the distance to the middle row gives one rule for the whole shape.

Examples

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

Hints

Hint 1

Think of the top half and the bottom half separately.

Hint 2

For row r, work out how many spaces and how many stars it has.

Hint 3

Use nested loops: one for the rows and others for the characters.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);
    int middle = n / 2;
    for (int r = 0; r < n; r++) {
        int distance = r < middle ? middle - r : r - middle;
        for (int s = 0; s < distance; s++) {
            printf(" ");
        }
        for (int s = 0; s < n - 2 * distance; s++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}

Lesson: Loops: for, while and do-while →