Дополнить двумерный массив строкой и столбцом, в которые записать суммы элементов - C#
Формулировка задачи:
Задан двумерный массив размерности m n. Дополнить его строкой и столбцом, в которых записать суммы элементов соответствующих строк и столбцов исходного массива. В элементе (m+1,n+1) должна храниться сумма всех элементов первоначального массива.
Решение задачи: «Дополнить двумерный массив строкой и столбцом, в которые записать суммы элементов»
textual
Листинг программы
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Random r = new Random();
Console.Write("M = "); int m = int.Parse(Console.ReadLine());
Console.Write("N = "); int n = int.Parse(Console.ReadLine());
int[,] mas = new int[m, n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
mas[i, j] = r.Next(0, 100);
Console.WriteLine("Исходная матрица:");
Output(mas);
mas = NewMas(mas);
Console.WriteLine("Новая матрица");
Output(mas);
Console.ReadKey();
}
static int[,] NewMas(int[,] mas)
{
int[,] mas1 = new int[mas.GetLength(0) + 1, mas.GetLength(1) + 1];
int global = 0;
for (int i = 0; i < mas1.GetLength(0) - 1; i++)
{
int sum = 0;
for (int j = 0; j < mas1.GetLength(1); j++)
if (j < mas.GetLength(1))
{
mas1[i, j] = mas[i, j];
sum += mas[i, j];
global += mas[i, j];
}
else
mas1[i, j] = sum;
}
for (int j = 0; j < mas1.GetLength(1) - 1; j++)
{
int sum = 0;
for (int i = 0; i < mas1.GetLength(0); i++)
if (i < mas.GetLength(0))
sum += mas[i, j];
else mas1[i, j] = sum;
}
mas1[mas.GetLength(0), mas.GetLength(1)] = global;
return mas1;
}
static void Output(int[,] mas)
{
for (int i = 0; i < mas.GetLength(0); i++)
{
for (int j = 0; j < mas.GetLength(1); j++)
Console.Write(mas[i, j] + "\t");
Console.WriteLine();
}
}
}
}