Introduction
The half diamond pattern is characterized by its diamond-like shape, truncated at the center.
Understanding the Half Diamond Star Pattern
The half diamond star pattern is a visual representation of stars forming a diamond shape but only half of it. The pattern consists of rows of stars, where the number of stars in each row increases or decreases, creating the illusion of a diamond cut in half.
Consider the following example with a height of 5.
*
**
***
****
*****
****
***
**
*
In this pattern, the number of stars increases up to the middle row and then decreases in a symmetrical manner.
Code Implementation
#include <iostream>
int main() {
int height = 5;
// Upper half of the diamond
for (int i = 1; i <= height; ++i) {
for (int j = 1; j <= i; ++j) {
std::cout << "* ";
}
std::cout << std::endl;
}
// Lower half of the diamond
for (int i = height - 1; i >= 1; --i) {
for (int j = 1; j <= i; ++j) {
std::cout << "* ";
}
std::cout << std::endl;
}
return 0;
}
Explanation
- The first loop (
for (int i = 1; i <= height; ++i)
) controls the upper half of the diamond, incrementing the number of stars in each row. - The second loop (
for (int i = height - 1; i >= 1; --i)
) controls the lower half of the diamond, decrementing the number of stars in each row. - The inner loop (
for (int j = 1; j <= i; ++j)
) in both cases prints the stars in each row. - The
std::endl
is used to move to the next line after printing each row.
Complexity Analysis
Time Complexity: The time complexity of generating the half diamond pattern is O(n^2)
, where n
is the height of the diamond. Both the upper and lower halves contribute to the quadratic time complexity.
Space Complexity: The space complexity is O(1)
, constant, as the amount of memory used does not depend on the input size. The memory required for each iteration remains constant.