The Program in C# Program to Find Sum of right Diagonals of a Matrix is given below:
using System;
namespace RightDiagonalSum
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Codeauri Family, enter the number of rows and columns in the matrix: ");
int rows = int.Parse(Console.ReadLine());
int columns = int.Parse(Console.ReadLine());
int[,] matrix = new int[rows, columns];
int sum = 0;
Console.WriteLine("Enter the elements of the matrix: ");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
matrix[i, j] = int.Parse(Console.ReadLine());
}
}
for (int i = 0; i < rows; i++)
{
sum += matrix[i, i];
}
Console.WriteLine("Okay, the sum of right diagonals is: " + sum);
}
}
}
Output:
Hello Codeauri Family, enter the number of rows and columns in the matrix:
3
3
Enter the elements of the matrix: 56
78
45
65
33
45
23
12
56
Okay, the sum of right diagonals is: 145
Pro-Tips💡
Here are the steps by steps execution of above program:
- We start by importing the
System
namespace. - Then, we create a class
Program
and aMain
method. - Next, we ask the user to enter the number of rows and columns in the matrix.
- We then declare two variables,
rows
andcolumns
to store the number of rows and columns entered by the user. - We create a 2-dimensional array
matrix
to store the elements of the matrix, and a variablesum
to store the sum of right diagonals. - We then ask the user to enter the elements of the matrix.
- We use a for loop to traverse the matrix, and for each element, we add the value of the current element (i, i) to the sum if the current row number is equal to the current column number.
- Finally, we print the sum of right diagonals.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.