Tech Point Fundamentals

Friday, February 4, 2022

C# Program to Find the Sum of Diagonal of Array

C# Program to Find the Sum of Diagonal of Array

coding-interview-question-csharp

Most of the IT companies check the coding skills and problem-solving skills as well along with the theoretical interview questions. Sometimes you are free to write the pseudo code and sometimes you are asked to write the complete program either on any paper or any editor. 


This question is asked in the coding interview to write the program. Here you can find the program as well as a live running program so that you can test the program immediately.


Watch our videos here





Question: 


Write a program to find the sum of the diagonal of a 2D array. or Write a program to print the diagonal elements and diagonal sum of an array.










C# Program to Find Sum of Array Diagonal Element


       
 

// Author 	: Tech Point Fundamentals
// Website 	: www.techpointfunda.com
// Channel	: https://www.youtube.com/c/TechPointFundamentals
// Demo		: Sum of the 2D Array Diagonal

using System;

public class Program
{
public static void Main()
{
	int[,] array = {
			{1, 6, 3, 2, 5},
			{2, 7, 2, 8, 7},
			{3, 8, 1, 6, 4},
			{4, 9, 0, 5, 0},
			{5, 4, 7, 3, 9}
			};			
			
	 int rowlength = 	array.GetLength(0);
	 int columnLength = array.GetLength(1);
	
	Console.WriteLine("Input 2D Array : ");	
	Console.WriteLine("------------------------------------------------ ");	
	
	for( int row = 0; row < rowlength; row++)
	{
		for( int col = 0; col < columnLength; col++)
		{
			Console.Write(array[row,col] +  " ");
		}
		Console.WriteLine();
	}			
	ArrayDiagonal(array, rowlength, columnLength);					
}	
	
public static void ArrayDiagonal(int[,] array, int rowLength, int colLength)    
{     
	int sum = 0;
	
	Console.WriteLine("\n\nDiagonal Array Element: ");	
	Console.WriteLine("------------------------------------------------ ");	
	
	for(int row = 0; row < rowLength; row++)
	{ 
		for(int column = 0; column < colLength; column++)
		{
			Console.Write("  ");
			if(row == column)
			{
				Console.Write( array[row,column] + " ");
				sum += array[row,column];
			}
		}
		Console.WriteLine();
	}		
	Console.WriteLine("\n\nDiagonal Array Element Sum : " + sum);		
} 	
}





Output: 



                Input 2D Array : ------------------------------------------------ 1 6 3 2 5 2 7 2 8 7 3 8 1 6 4 4 9 0 5 0 5 4 7 3 9 Diagonal Array Element: ------------------------------------------------ 1 7 1 5 9 Diagonal Array Element Sum : 23


Live Demo






No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.