C++ Online Compiler
Example: Matrix with Alternating Rectangles in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Matrix with Alternating Rectangles #include <iostream> #include <vector> #include <algorithm> // Required for std::min // Helper function to print the matrix void printMatrix(const std::vector<std::vector<char>>& matrix) { for (const auto& row : matrix) { for (char c : row) { std::cout << c << " "; } std::cout << std::endl; } } int main() { // Step 1: Define matrix dimensions // You can change these values to create matrices of different sizes int rows = 7; int cols = 7; // Ensure valid dimensions if (rows <= 0 || cols <= 0) { std::cout << "Matrix dimensions must be positive." << std::endl; return 1; } // Step 2: Initialize the matrix // Using a vector of vectors for dynamic sizing and easy manipulation std::vector<std::vector<char>> matrix(rows, std::vector<char>(cols)); // Step 3: Fill the matrix with alternating 'O' and 'X' rectangles // The loop iterates through layers, starting from the outermost (k=0) // The loop continues as long as there's an inner rectangle to fill. // k * 2 represents the total width/height consumed by 'k' layers from both sides. // If k * 2 is less than min(rows, cols), there's still a central region or a new layer. for (int k = 0; k * 2 < std::min(rows, cols); ++k) { // Determine the character for the current layer based on 'k' (layer index) // Layer 0, 2, 4... get 'O'. Layer 1, 3, 5... get 'X'. char charToFill = (k % 2 == 0) ? 'O' : 'X'; // Calculate the boundaries for the current layer int rowStart = k; int rowEnd = rows - 1 - k; int colStart = k; int colEnd = cols - 1 - k; // Fill the current rectangular layer's boundaries // Fill top edge: from colStart to colEnd in rowStart for (int j = colStart; j <= colEnd; ++j) { matrix[rowStart][j] = charToFill; } // Fill bottom edge: from colStart to colEnd in rowEnd // Only fill if rowStart and rowEnd are distinct (i.e., not a single-row matrix or innermost single cell) if (rowStart < rowEnd) { for (int j = colStart; j <= colEnd; ++j) { matrix[rowEnd][j] = charToFill; } } // Fill left edge: from rowStart to rowEnd in colStart // Corners are already filled by the horizontal passes; it's harmless to overwrite them with the same character. for (int i = rowStart; i <= rowEnd; ++i) { matrix[i][colStart] = charToFill; } // Fill right edge: from rowStart to rowEnd in colEnd // Only fill if colStart and colEnd are distinct (i.e., not a single-column matrix or innermost single cell) if (colStart < colEnd) { for (int i = rowStart; i <= rowEnd; ++i) { matrix[i][colEnd] = charToFill; } } } // Step 4: Print the resulting matrix std::cout << "Generated Matrix (" << rows << "x" << cols << "):" << std::endl; printMatrix(matrix); return 0; }
Output
Clear
ADVERTISEMENTS