Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,705 questions

55,464 answers

573 users

How to generate an n x n matrix filled with elements from 1 to N^2 in spiral order in C#

1 Answer

0 votes
using System;

class SpiralMatrixGenerator
{
    public static int[,] GenerateSpiralMatrix(int n) {
        int[,] matrix = new int[n, n];
        int top = 0, bottom = n - 1;
        int left = 0, right = n - 1;
        int num = 1;

        while (top <= bottom && left <= right) {
            // Fill top row
            for (int i = left; i <= right; i++)
                matrix[top, i] = num++;
            top++;

            // Fill right column
            for (int i = top; i <= bottom; i++)
                matrix[i, right] = num++;
            right--;

            // Fill bottom row
            if (top <= bottom) {
                for (int i = right; i >= left; i--)
                    matrix[bottom, i] = num++;
                bottom--;
            }

            // Fill left column
            if (left <= right) {
                for (int i = bottom; i >= top; i--)
                    matrix[i, left] = num++;
                left++;
            }
        }

        return matrix;
    }

    public static void Main()
    {
        int n = 3; // size of the matrix
        int[,] spiralMatrix = GenerateSpiralMatrix(n);

        // Print the matrix
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                Console.Write(spiralMatrix[i, j] + "\t");
            }
            Console.WriteLine();
        }
    }
}




/*
run:

1	2	3	
8	9	4	
7	6	5

*/

 



answered Jun 24, 2025 by avibootz
...