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:

C# Program to Display Lower Triangular Matrix

Share:

Leave a Reply

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...