Write a program in C# that finds the sum of diagonal elements of a mxn matrix.
Following is the simple C# code :
Following is the simple C# code :
class Lab { static void Main(string[] args) { int h, v, rows, cols; int[,] myArray = new int[50, 50]; Console.WriteLine("Enter Row Value"); rows = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter Column Value"); cols = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter Elements one by one"); for (h = 1; h <= rows; h++) { for (v = 1; v <= cols; v++) { myArray[h, v] = Convert.ToInt32(Console.ReadLine()); } } Console.WriteLine("Given Matrix"); for (h = 1; h <= rows; h++) { for (v = 1; v <= cols; v++) { Console.Write("\t{0}", myArray[h, v]); } Console.WriteLine(); } int digonalSum1 = 0; int digonalSum2 = 0; if (rows == cols) { for (h = 1; h <= rows; h++) { for (v = 1; v <= cols; v++) { if (h == v) { digonalSum1 = digonalSum1 + myArray[h, v]; } } digonalSum2 = digonalSum2 + myArray[h, cols - h + 1]; } Console.WriteLine("Diagonal Sum= {0}", digonalSum1); Console.WriteLine("Diagonal Sum= {0}", digonalSum2); } else { Console.WriteLine("Can't Perform Diagonal Sum"); } Console.Read(); } }
Output:-
Enter Row Value 2 Enter Column Value 2 Enter Elements one by one 1 2 3 4 Given Matrix 1 2 3 4 Diagonal Sum= 5 Diagonal Sum= 5
No comments:
Post a comment