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:

C# Program to Display Lower Triangular Matrix

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...