MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

C++ Program to Print Diamond Pattern with Explanation

C++ Medium Pattern Printing 29 views
This problem helps you practice core C++ fundamentals in a practical way. It builds intuition around diamond, complete, shape. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Print complete diamond shape.
Real Life: Combining pyramid and inverted pyramid.

Input Format

An integer n (number of rows for the upper half).

Output Format

Complete diamond shape using *.

Constraints

• n ≥ 1

• Use loops only

Concept Explanation

A complete diamond is made by combining a pyramid and an inverted pyramid.
Stars increase first, then decrease, while spaces keep the shape centered.

Step-by-Step Logic

Upper Half (Pyramid)

1.Loop row i from 1 to n.

2.Print (n - i) spaces.

3.Print (2*i - 1) stars.

4.Move to next line.

Lower Half (Inverted Pyramid)
5. Loop row i from n-1 to 1.
6. Print (n - i) spaces.
7. Print (2*i - 1) stars.
8. Move to next line.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
void pattern_q8_diamond() { int n = 5; // Upper pyramid for(int i = 1; i <= n; i++) { for(int j = 1; j <= n - i; j++) { cout << " "; } for(int k = 1; k <= 2*i - 1; k++) { cout << "*"; } cout << endl; } // Lower inverted pyramid for(int i = n - 1; i >= 1; i--) { for(int j = 1; j <= n - i; j++) { cout << " "; } for(int k = 1; k <= 2*i - 1; k++) { cout << "*"; } cout << endl; } }

Output Example

Input:
4
Output:
* *** ***** ******* ***** *** *

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next