C#: Find the sum of rows an columns of a Matrix
C# Sharp Array: Exercise-25 with Solution
Write a C# Sharp program to find the sum of rows and columns in a matrix.
Sample Solution:-
C# Sharp Code:
using System;
public class Exercise25
{
public static void Main()
{
int i, j, n; // Declare variables for iteration and matrix size
int[,] arr1 = new int[10, 10]; // Declare a 2D array to store the matrix
int[] rsum = new int[10]; // Declare an array to store the sum of rows
int[] csum = new int[10]; // Declare an array to store the sum of columns
Console.Write("\n\nFind sum of row and column of a Matrix:\n");
Console.Write("-------------------------------------------\n");
Console.Write("Input the size of the square matrix : ");
n = Convert.ToInt32(Console.ReadLine()); // Input the size of the square matrix
Console.Write("Input elements in the matrix :\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
Console.Write("element - [{0}],[{1}] : ", i, j);
arr1[i, j] = Convert.ToInt32(Console.ReadLine()); // Input matrix elements
}
}
Console.Write("The matrix is :\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
Console.Write("{0} ", arr1[i, j]); // Display the matrix
}
Console.Write("\n");
}
/* Calculate sum of rows */
for (i = 0; i < n; i++)
{
rsum[i] = 0; // Initialize sum for each row to zero
for (j = 0; j < n; j++)
{
rsum[i] += arr1[i, j]; // Calculate sum of each row
}
}
/* Calculate sum of columns */
for (i = 0; i < n; i++)
{
csum[i] = 0; // Initialize sum for each column to zero
for (j = 0; j < n; j++)
{
csum[i] += arr1[j, i]; // Calculate sum of each column
}
}
Console.Write("The sum of row and column of the matrix :\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
Console.Write("{0} ", arr1[i, j]); // Display the matrix elements
}
Console.Write("{0} ", rsum[i]); // Display sum of each row
Console.Write("\n");
}
// Display sum of each column separately
for (j = 0; j < n; j++)
{
Console.Write("{0} ", csum[j]);
}
Console.Write("\n\n");
}
}
Sample Output:
Find sum of row and column of a Matrix: ------------------------------------------- Input the size of the square matrix : 2 Input elements in the matrix : element - [0],[0] : 2 element - [0],[1] : 4 element - [1],[0] : 6 element - [1],[1] : 8 The matrix is : 2 4 6 8 The sum of row and column of the matrix : 2 4 6 6 8 14 8 12
Flowchart:
C# Sharp Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a program in C# Sharp to find sum of left diagonals of a matrix.
Next: Write a program in C# Sharp to print or display the lower triangular of a given matrix.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/csharp-exercises/array/csharp-array-exercise-25.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics