At school we were assigned a task in C# programming:
Create a magic square (siamese method) that can create any size, odd squares.
using System;
class Program
{
static void Main(string[] args)
{
bool correctInput = false;
int n = 0;
while (!correctInput) {
Console.WriteLine("Input an odd number:");
string input = Console.ReadLine();
if (!int.TryParse(input, out n)) {
Console.WriteLine("This is not a number '" + input + "'!\nPress any key to retry");
Console.ReadLine(); } else if (Convert.ToInt16(input) % 2 == 0) {
Console.WriteLine("This is not an odd number '" + input +"'!\nPress any key to retry");
Console.ReadLine(); } else {
n = Convert.ToInt16(input);
correctInput = true; } }
int nSquare = n * n;
int y = 0;
int x = (n / 2);
int[,] magicSquare = new int[n, n];
for (int a = 1; a <= nSquare; ++a) {
magicSquare[y, x] = a;
y--;
x++;
if (a % n == 0) {
y += 2;
x -= 1; } else {
x = (x + n) % n;
y = (y + n) % n; }
}
for (int a = 0; a < n; a++) {
for (int b = 0; b < n; b++) {
Console.Write(Convert.ToString(magicSquare[a, b]).PadLeft((Convert.ToString(nSquare).Length), ' ') + " "); }
Console.WriteLine(""); }
}
}
That’s how it turned out.