Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Diamond Pattern in C++

Print a diamond of stars in C++ by stacking a full pyramid on an inverted pyramid one row shorter. Covers the half-height input and the doubled-row bug.

IntermediateAdvanced Pattern ProgramsExample 3 of 6
diamond-pattern.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int rows;
6
7 cout << "Enter number of rows (half): ";
8 cin >> rows;
9
10 // Upper part of diamond
11 for (int i = 1; i <= rows; i++) {
12 for (int j = 1; j <= rows - i; j++) {
13 cout << " ";
14 }
15 for (int j = 1; j <= 2 * i - 1; j++) {
16 cout << "*";
17 }
18 cout << endl;
19 }
20
21 // Lower part of diamond
22 for (int i = rows - 1; i >= 1; i--) {
23 for (int j = 1; j <= rows - i; j++) {
24 cout << " ";
25 }
26 for (int j = 1; j <= 2 * i - 1; j++) {
27 cout << "*";
28 }
29 cout << endl;
30 }
31
32 return 0;
33}

Sample Output

*********

The middle row, printed once.

In this one

  • How two pyramids join to form a diamond
  • Why the lower half starts at rows - 1
  • How the half-height input gives 2 × rows − 1 lines
  • How the same formulas serve both halves

How it works

  1. 1

    Read the half height (5).

  2. 2

    Upper loop: i = 1 to 5, spaces rows - i, stars 2i - 1.

  3. 3

    Lower loop: i = 4 down to 1 with the same formulas.

  4. 4

    Total of 9 lines.

Edge cases

Lower loop starting at rows

Start the second loop at rows.

The widest 9-star line prints twice, making a flat middle.

Half height 1

Enter 1.

The upper loop prints one star and the lower loop does not run, so the diamond is a single *.

What's going on

A diamond is a full pyramid glued to an inverted pyramid, without printing the fat middle twice.

cin >> rows; is the half-height. Sample 5 → 9 lines total (5 up, 4 down).

Upper half — identical to Full Pyramid:

spaces rows - i, stars 2 * i - 1. i = 1..rows → 1, 3, 5, 7, 9 stars.

Lower half:

for (int i = rows - 1; i >= 1; i--)

Start at rows - 1, not rows. Start at rows and the 9-star line prints twice and it looks like a stretched hexagon.

Same space/star formulas. i = 4, 3, 2, 1 → 7, 5, 3, 1 stars.

Prompt says "half". Type 5 expecting 5 lines and you'll get 9. That's the API.

Hollow diamond is the same two loops with the hollow if on stars. This file is solid.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Half height 4 gives how many lines?

Pick an answer to check it.

Question 2

What is the widest row for half height 6?

Pick an answer to check it.

Questions people ask

How many lines does the diamond have?

2 × rows − 1.

Can I make it hollow?

Yes, print stars only at the first and last positions of each row.

Why is the input called half?

It sets the height of the top half including the middle row.