Вы можете использовать этот исправленный
int[,] array1 = new int[6, 6]
{
{10, 20, 10, 20, 21, 99 },
{2, 27, 5, 45, 20, 13 },
{17, 20, 20, 33, 33, 20 },
{21, 35, 15, 54, 20, 37 },
{31, 101, 25, 55, 26, 66 },
{45, 20, 44, 12, 55, 98 }
};
int Length = array1.GetLength(0);
int Height = array1.GetLength(1);
int CalculateRow = 0;
Console.Write("Enter the number of the Row you would like to see the sum of: ");
int h = Convert.ToInt32(Console.ReadLine());
if ( h < 0 || h >= Length )
{
Console.Write(-1);
}
else
{
for ( int j = 0; j < Height; j++ )
{
CalculateRow = CalculateRow + array1[h, j];
}
Console.WriteLine("The sum of Row {0} is {1} ", h, CalculateRow);
}
. Мы просим пользователя ввести индекс строки перед выполнением цикла по элементам выбранной строки, чтобы получить сумму.
Вы можете выполнить рефакторинг переменных
Чтобы иметь более согласованное и релевантное наименование, чтобы оно было более чистым.
А также используйте TryParse вместо Convert: он возвращаетfalse, если входная строка не может быть преобразована вместо исключения.
Например,
int[,] matrix = new int[6, 6]
{
{10, 20, 10, 20, 21, 99 },
{2, 27, 5, 45, 20, 13 },
{17, 20, 20, 33, 33, 20 },
{21, 35, 15, 54, 20, 37 },
{31, 101, 25, 55, 26, 66 },
{45, 20, 44, 12, 55, 98 }
};
int rowsCount = matrix.GetLength(0);
int columnsCount = matrix.GetLength(1);
int rowSum = 0;
Console.Write("Enter the number of the Row you would like to see the sum of ");
Console.Write("(0 to " + (rowsCount - 1) + "): ");
if ( !int.TryParse(Console.ReadLine(), out var rowIndex)
|| rowIndex < 0
|| rowIndex >= rowsCount )
{
Console.Write("Wrong index.");
}
else
{
for ( int columnIndex = 0; columnIndex < columnsCount; columnIndex++ )
{
rowSum = rowSum + matrix[rowIndex, columnIndex];
}
Console.WriteLine("The sum of Row {0} is {1} ", rowIndex, rowSum);
}
Для отображения суммы каждой строки
for ( int rowIndex = 0; rowIndex < rowsCount; rowIndex++ )
{
rowSum = 0; // reset the sum between rows
for ( int columnIndex = 0; columnIndex < columnsCount; columnIndex++ )
{
rowSum = rowSum + matrix[rowIndex, columnIndex];
}
Console.WriteLine("The sum of Row {0} is {1} ", rowIndex, rowSum);
}
Результат
The sum of Row 0 is 180
The sum of Row 1 is 112
The sum of Row 2 is 143
The sum of Row 3 is 182
The sum of Row 4 is 304
The sum of Row 5 is 274