C Online Compiler
Example: Generate Spiral Matrix
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Generate Spiral Matrix #include
// Function to print the matrix void printMatrix(int N, int matrix[N][N]) { printf("Generated Spiral Matrix:\n"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { printf("%4d", matrix[i][j]); // Print with spacing for alignment } printf("\n"); } } int main() { // Step 1: Define matrix size N int N; printf("Enter the size of the square matrix (N): "); scanf("%d", &N); // Step 2: Declare the N x N matrix int matrix[N][N]; // Step 3: Initialize boundary pointers and current number int top = 0, bottom = N - 1; int left = 0, right = N - 1; int currentNum = 1; // Start filling from 1 // Step 4: Loop until all elements are filled (boundaries cross) while (top <= bottom && left <= right) { // Fill from left to right along the top row for (int i = left; i <= right; i++) { matrix[top][i] = currentNum++; } top++; // Move top boundary down // Fill from top to bottom along the right column for (int i = top; i <= bottom; i++) { matrix[i][right] = currentNum++; } right--; // Move right boundary left // Check if top boundary is still less than or equal to bottom boundary // This is crucial for non-square matrices, though here N x N // It prevents re-traversing if only a single row or column is left if (top <= bottom) { // Fill from right to left along the bottom row for (int i = right; i >= left; i--) { matrix[bottom][i] = currentNum++; } bottom--; // Move bottom boundary up } // Check if left boundary is still less than or equal to right boundary // Similar to the check for top <= bottom if (left <= right) { // Fill from bottom to top along the left column for (int i = bottom; i >= top; i--) { matrix[i][left] = currentNum++; } left++; // Move left boundary right } } // Step 5: Print the generated matrix printMatrix(N, matrix); return 0; }
Output
Clear
ADVERTISEMENTS