Learn Programming and technology with ease @ developerpublish.com

HomeCSharpC# Program to Display Lower Triangular Matrix

C# Program to Display Lower Triangular Matrix

In linear algebra, a lower triangular matrix is a square matrix in which all the elements above the main diagonal are zero. In this C# program, we will generate and display a lower triangular matrix.

Problem Statement:

Write a C# program that takes an integer â€˜nâ€™ as input and generates a lower triangular matrix of size â€˜n x nâ€™ with random values for the elements below or on the main diagonal. Then, it will display the matrix.

C# Program to Display Lower Triangular Matrix

```using System;

class LowerTriangularMatrix
{
static void Main()
{
Console.WriteLine("Lower Triangular Matrix Generator");
Console.Write("Enter the size of the matrix (n): ");
int n = int.Parse(Console.ReadLine());

int[,] matrix = GenerateLowerTriangularMatrix(n);

Console.WriteLine("\nLower Triangular Matrix:");
DisplayMatrix(matrix);
}

static int[,] GenerateLowerTriangularMatrix(int n)
{
int[,] matrix = new int[n, n];
Random rand = new Random();

for (int i = 0; i < n; i++)
{
for (int j = 0; j <= i; j++)
{
matrix[i, j] = rand.Next(1, 101); // Fill with random values (1-100)
}
}

return matrix;
}

static void DisplayMatrix(int[,] matrix)
{
int n = matrix.GetLength(0);

for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(matrix[i, j] + "\t");
}
Console.WriteLine();
}
}
}
```

How it Works:

1. The program starts by taking input for the size of the matrix â€˜nâ€™.
2. The `GenerateLowerTriangularMatrix` function generates a lower triangular matrix of size â€˜n x nâ€™ with random values below or on the main diagonal.
3. The `DisplayMatrix` function is used to display the generated matrix.
4. The generated lower triangular matrix is displayed on the console.

Input/Output:

Share:

You May Also Like

C# Program to Display Upper Triangular Matrix

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...

C# Program to Demonstrate Bitwise Operators

This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...

C# Program to Interchange the Columns of a Matrix

This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...