C Online Compiler
Example: Alternating Rectangle Matrix in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Alternating Rectangle Matrix #include <stdio.h> void printMatrix(char matrix[100][100], int rows, int cols) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%c ", matrix[i][j]); } printf("\n"); } } int main() { int rows, cols; // Step 1: Get matrix dimensions from the user printf("Enter number of rows (max 100): "); scanf("%d", &rows); printf("Enter number of columns (max 100): "); scanf("%d", &cols); // Basic validation for dimensions if (rows <= 0 || cols <= 0 || rows > 100 || cols > 100) { printf("Invalid dimensions. Please enter positive numbers up to 100.\n"); return 1; } // Step 2: Declare the matrix char matrix[100][100]; // Step 3: Initialize boundary variables and fill character int top = 0; int bottom = rows - 1; int left = 0; int right = cols - 1; char fill_char = 'O'; // Start with 'O' for the outermost layer // Step 4: Loop to fill layers until boundaries cross while (top <= bottom && left <= right) { // Fill top row for (int i = left; i <= right; i++) { matrix[top][i] = fill_char; } top++; // Move top boundary inwards // Fill right column for (int i = top; i <= bottom; i++) { matrix[i][right] = fill_char; } right--; // Move right boundary inwards // Fill bottom row (only if valid row exists) if (top <= bottom) { for (int i = right; i >= left; i--) { matrix[bottom][i] = fill_char; } bottom--; // Move bottom boundary inwards } // Fill left column (only if valid column exists) if (left <= right) { for (int i = bottom; i >= top; i--) { matrix[i][left] = fill_char; } left++; // Move left boundary inwards } // Switch character for the next layer fill_char = (fill_char == 'O') ? 'X' : 'O'; } // Step 5: Print the resulting matrix printf("\nGenerated Matrix:\n"); printMatrix(matrix, rows, cols); return 0; }
Output
Clear
ADVERTISEMENTS