Math Student
Math Student

Reputation: 567

How to read a matrix from the console and print the sum of all matrix elements

I'm learning C#, and now I am on Multidimensional Arrays. I want to write a program that reads a matrix from the console and print:

So, on the next [rows] lines I will get elements for each column separated with comma and space. I made a foreach for the sum but I do not understand how to insert the elements into the matrix. I would be very grateful if you could help me!

int[] dimensions = Console.ReadLine()
.Split(", ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray(); 

int rows = dimensions[0];
int columns = dimensions[1];

int[,] matrix = new int[rows,columns];

for (int i = 0; i < rows; i++)
{ 
    int[] numbers = Console.ReadLine()
        .Split(", ", StringSplitOptions.RemoveEmptyEntries)
        .Select(int.Parse)
        .ToArray();
//I do not know how to add the elements here
}

int sum = 0;
foreach (var element in matrix)
{
    sum += element;
}

Upvotes: 1

Views: 1065

Answers (2)

Renat
Renat

Reputation: 8972

Elements in 2-d array are being accessed using two indices:

for (int i = 0; i < rows; i++)
{ 
    int[] numbers = Console.ReadLine()
        .Split(", ", StringSplitOptions.RemoveEmptyEntries)
        .Select(int.Parse)
        .ToArray();

    for (int j = 0; j < columns; j++)
    {
        matrix[i,j]=numbers[j];
    }
}

int sum = 0;
for (int i = 0; i < rows; i++)
{ 
    for (int j = 0; j < columns; j++)
    {
        sum += matrix[i,j];
    }
}

Upvotes: 1

Prasad Telkikar
Prasad Telkikar

Reputation: 16079

You can use Linq Sum() to calculate sum for all rows

As you are iterating through each row of input data already, then you can assign one temparary variable called sum =0 and for each row calculate sum of all numbers of that row and add it to temporary variable i.e. sum.

int sum = 0;
for (int i = 0; i < rows; i++)
{ 
    int[] numbers = Console.ReadLine()
        .Split(", ", StringSplitOptions.RemoveEmptyEntries)
        .Select(int.Parse)
        .ToArray();
    sum += numbers.Sum(); //Calculate sum of all numbers in a row and add it to existing sum variable.
//I do not know how to add the elements here
}

Console.WriteLine("Sum of all numbers" + sum); //print sum of all numbers i.e. 76

Upvotes: 2

Related Questions