daniell e
daniell e

Reputation: 15

Magic square array filled with random numbers doesn't accept even numbers

I found this code that i need for an assigment, but it only reads odd numbers and i need it to read even numbers too, but i don't know whats wrong. I need it to make the random magic squares go from 1 to 10.

Still very much a beginner and don't understand functions yet, please let me know if there is a way to dolve this.

using System;
class GFG
{
    // Function to generate odd sized magic squares
    static void generateSquare(int n)
    {
        int[,] magicSquare = new int[n, n];

        // Initialize position for 1
        int i = n / 2;
        int j = n - 1;

        // One by one put all values in magic square
        for (int num = 1; num <= n * n;)
        {
            if (i == -1 && j == n) // 3rd condition
            {
                j = n - 2;
                i = 0;
            }
            else
            {
                // 1st condition helper if next number
                // goes to out of square's right side
                if (j == n)
                    j = 0;

                // 1st condition helper if next number is
                // goes to out of square's upper side
                if (i < 0)
                    i = n - 1;
            }

            // 2nd condition
            if (magicSquare[i, j] != 0)
            {
                j -= 2;
                i++;
                continue;
            }
            else
                // set number
                magicSquare[i, j] = num++;

            // 1st condition
            j++;
            i--;
        }

        // print magic square
        Console.WriteLine("The Magic Square for " + n
                          + ":");
        Console.WriteLine("Sum of each row or column "
                          + n * (n * n + 1) / 2 + ":");

        for (i = 0; i < n; i++)
        {
            for (j = 0; j < n; j++)
                Console.Write(magicSquare[i, j] + " ");
            Console.WriteLine();
        }
    }

    // driver program
    public static void Main()
    {
        Console.WriteLine("Value of n: ");
        int n = int.Parse(Console.ReadLine());
        // Works only when n is odd

        generateSquare(n);
    }
}

Upvotes: -1

Views: 167

Answers (1)

Jeff Matchett
Jeff Matchett

Reputation: 83

Step through the program with a debugger. Using n = 2 as an example, on your second loop through the for loop you get to this with i = 1 and j = 1:

if (magicSquare[i, j] != 0)
    {
        j -= 2;
        i++;
        continue;
    }

And that makes i = 2 on the next loop through. Because there is no 2 index in the array you have created, it crashes when it gets to this same check the next loop.

Presumably odd numbers are working because they are getting floored on division (in the case of n = 5 -> i = 2).

That should be enough to point you in the right direction.

Upvotes: 0

Related Questions