Заполнить массив элементами главной диагонали матрицы - C#
Формулировка задачи:
Заполните одномерный массив положительными элементами, расположенные на главной диагонали заданного квадратного массива. Выведите полученный массив на экран и найдите произведение элементов. Используйте подпрограммы для решения каждой частной задачи.
Решение задачи: «Заполнить массив элементами главной диагонали матрицы»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
public static Random rnd = new Random();
public static int[] GenArray(int[,] array)
{
int[] result = new int[array.GetLength(0)];
for (int i = 0; i < array.GetLength(0); i++)
result[i] = array[i, i];
return result;
}
public static int GetProduct(int[] array)
{
int prod = 1;
for (int i = 0; i < array.Length; i++)
prod *= array[i];
return prod;
}
static void Main(string[] args)
{
var array2d = new int[8, 8];
for (int i = 0; i < array2d.GetLength(0); i++)
for (int j = 0; j < array2d.GetLength(1); j++)
array2d[i, j] = rnd.Next(-10,11);
var array = GenArray(array2d);
Console.WriteLine("массив из главной диагонали:");
Console.WriteLine(string.Join(" ", array));
int product = GetProduct(array);
Console.WriteLine($"его произведение: {product}");
Console.WriteLine();
Console.ReadKey(true);
}
}
}