Creating a full diamond shape pyramid using characters in C++ involves using nested loops to print spaces and characters in a specific format. This pattern is visually appealing and commonly used to practice loop constructs. The diamond pattern consists of two parts: an upper pyramid and an inverted lower pyramid.
Example: Full Diamond Shape Pyramid Using Stars (*)
This program will print a diamond shape pyramid made of stars (*). The user will input the number of rows for the upper pyramid. The lower pyramid will automatically be one row less than the upper to complete the diamond shape.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int rows;
// User inputs the number of rows for the upper part of the diamond
cout << “Enter the number of rows: “;
cin >> rows;
// Print the upper part of the diamond
for (int i = 1; i <= rows; ++i) {
// Print leading spaces
for (int j = rows – i; j > 0; –j) {
cout << ” “;
}
// Print stars
for (int j = 1; j <= 2 * i – 1; ++j) {
cout << “*”;
}
cout << endl;
}
// Print the lower part of the diamond
for (int i = rows – 1; i > 0; –i) {
// Print leading spaces
for (int j = 0; j < rows – i; ++j) {
cout << ” “;
}
// Print stars
for (int j = 1; j <= 2 * i – 1; ++j) {
cout << “*”;
}
cout << endl;
}
return 0;
}
Explanation:
-
Header and Namespace:
The program includes the <iostream> header for input and output operations and uses the std namespace.
- Input:
The user is prompted to enter the number of rows for the upper half of the diamond.
-
Upper Diamond:
- Outer Loop: Controls the rows of the upper pyramid.
- First Inner Loop: Manages the spaces before the stars begin on each row. The spaces decrease as the row number increases.
- Second Inner Loop: Manages the printing of stars. The number of stars on each row is 2 * i – 1, forming the pyramid shape.
-
Lower Diamond:
- Outer Loop: Controls the rows of the lower inverted pyramid.
- First Inner Loop: Similar to the upper half but in reverse order for spaces.
- Second Inner Loop: Handles the printing of stars, decreasing the count as the rows decrease to form the inverted pyramid.
Program Output:
If the user inputs 4 for the number of rows, the output will be:
*
***
*****
*******
*****
***
*