C++ Online Compiler
Example: Hollow Diamond Inscribed in a Rectangle in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Hollow Diamond Inscribed in a Rectangle #include <iostream> // Required for input/output operations (cin, cout) #include <cmath> // Required for the abs() function int main() { // Step 1: Get the size from the user // The input 'n' determines the 'radius' of the diamond and // thus the overall dimensions of the square grid (2*n - 1 by 2*n - 1). int n; std::cout << "Enter the size for the diamond (e.g., 3 for a 5x5 grid): "; std::cin >> n; // Calculate total dimensions based on 'n' // A diamond with 'n' as its half-width/height will have // (2*n - 1) rows and (2*n - 1) columns. int total_rows = 2 * n - 1; int total_cols = 2 * n - 1; // The center row/column index of the grid int center_coord = n - 1; // Step 2: Iterate through each row and column of the grid for (int row = 0; row < total_rows; ++row) { for (int col = 0; col < total_cols; ++col) { // Step 3: Check conditions for printing '*' or ' ' // Condition for the rectangle border // An asterisk is printed if the cell is on the top, bottom, left, or right edge. bool is_rectangle_border = (row == 0 || row == total_rows - 1 || col == 0 || col == total_cols - 1); // Condition for the hollow diamond perimeter // A point (row, col) is on the perimeter of a diamond centered at (center_coord, center_coord) // with a 'radius' of center_coord if the sum of absolute differences // from the center equals the 'radius'. bool is_diamond_perimeter = (std::abs(row - center_coord) + std::abs(col - center_coord) == center_coord); // Step 4: Print '*' if either condition is met, otherwise print ' ' if (is_rectangle_border || is_diamond_perimeter) { std::cout << "*"; } else { std::cout << " "; } } // Move to the next line after each row is complete std::cout << std::endl; } return 0; }
Output
Clear
ADVERTISEMENTS