Loading...

Introduction

Diamond patterns are visually striking geometric designs that are often used for decorative purposes or in graphical interfaces. These patterns, characterized by a symmetrical arrangement of characters forming a diamond shape.

Understanding

A diamond pattern is essentially two triangular patterns stacked on top of each other, one ascending and the other descending. The key is to control the number of spaces and characters printed in each row to achieve symmetry. The pattern often involves nested loops to manage the spacing and characters at each position.

Let's visualize a diamond pattern with five rows:

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

Code Implementation

#include <iostream>

void printDiamond(int n) {
    // Ascending Triangle
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n - i - 1; ++j)
            std::cout << " ";
        for (int k = 0; k < 2 * i + 1; ++k)
            std::cout << "*";
        std::cout << std::endl;
    }

    // Descending Triangle
    for (int i = n - 2; i >= 0; --i) {
        for (int j = 0; j < n - i - 1; ++j)
            std::cout << " ";
        for (int k = 0; k < 2 * i + 1; ++k)
            std::cout << "*";
        std::cout << std::endl;
    }
}

int main() {
    int rows;

    // Input the number of rows for the diamond
    std::cout << "Enter the number of rows for the diamond pattern: ";
    std::cin >> rows;

    // Generate and display the diamond pattern
    printDiamond(rows);

    return 0;
}

Complexity Analysis

Time Complexity: The time complexity of the diamond pattern is O(n^2), where n is the number of rows. This is because there are nested loops used to iterate through each row and column to print the characters.

Space Complexity: The space complexity is O(1), as there is no additional memory used that scales with the input size. The memory used is constant.