وعليكم السلام ورحمة الله.
انت بحاجة فقط لمجموعة حلقات تكرارية loops للمرور على المصفوفة لتعبئتها اولا ثم لجمع الاسطر والاعمدة والاقطار.
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Read the array dimensions from the user
Console.Write("Enter the array size: ");
int size = int.Parse(Console.ReadLine());
// If the array size is even (not odd), then break;
if (size % 2 == 0)
{
Console.WriteLine("Please enter en odd number!");
return;
}
// Define our [Size x Size] array
int[,] array = new int[size, size];
// Assume that the array is magic until we make our calculations
bool isMagic = true;
// Just Print the array, to make it more readable
// We have 2 loops, one for rows and the other for columns
// It start from the [0,0], then [0,1] index until complete the first row
// Then complete for [1,0], then [1,1] index until complete the second row, and so on...
Console.WriteLine("Array size:");
for (int row = 0; row < size; row++)
{
for (int col = 0; col < size; col++)
{
Console.Write($"[{row},{col}]");
}
Console.WriteLine();
}
// Fill the array
// Also using 2 loops
Console.WriteLine();
Console.WriteLine("Please fill the array");
for (int row = 0; row < size; row++)
{
for (int col = 0; col < size; col++)
{
Console.Write($"Enter number at [{row},{col}]: ");
array[row, col] = int.Parse(Console.ReadLine());
}
}
// Start our calculations
Console.WriteLine();
Console.WriteLine("Calculating:");
// Sum the first row, where other rows, columns and diagonals must match
int magicValue = 0;
for (int i = 0; i < size; i++)
{
magicValue += array[i,0];
}
// We will start by calculating the first row sum and the first col sum.
for (int row = 0; row < size; row++)
{
int rowValue = 0;
int colValue = 0;
for (int col = 0; col < size; col++)
{
rowValue += array[col, row];
colValue += array[row, col];
}
// if the current row sum != magicValue then break
if(rowValue!= magicValue)
{
isMagic = false;
break;
}
// Also if the current column sum != magicValue then break
if(colValue!= magicValue)
{
isMagic = false;
break;
}
// first loop match
// Reset values to calcaute the rest of rows and cols.
rowValue = 0;
colValue = 0;
}
// If we reach this code without any break, then all rows and cols are matched
// we need to check if isMagic still true, and not flagged to false inside the loops.
if (isMagic)
{
// Print the final array
Console.WriteLine("It's Magic Array :)");
for (int row = 0; row < size; row++)
{
for (int col = 0; col < size; col++)
{
Console.Write($"[{array[row,col]}]");
}
Console.WriteLine();
}
}
else
{
Console.WriteLine("Not match");
}
}
}
}
يمكنك التجربة بمصفوفة بحجم 3x3
والمدخلات كالتالي:
[2][7][6]
[9][5][1]
[4][3][8]
بالتوفيق،،،