HomeCSharpC# Program to Display Upper Triangular Matrix

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 size of the matrix and the matrix elements as input and then generates and displays the upper triangular matrix.

C# Program to Display Upper Triangular Matrix

using System;

class UpperTriangularMatrix
{
    static void Main(string[] args)
    {
        Console.WriteLine("Upper Triangular Matrix Display");
        Console.WriteLine("--------------------------------");

        // Input the matrix size
        Console.Write("Enter the size of the matrix: ");
        int size = int.Parse(Console.ReadLine());

        int[,] matrix = new int[size, size];

        // Input the matrix elements
        Console.WriteLine("Enter the matrix elements:");
        for (int i = 0; i < size; i++)
        {
            for (int j = 0; j < size; j++)
            {
                if (j >= i)
                {
                    Console.Write($"Enter element at position [{i},{j}]: ");
                    matrix[i, j] = int.Parse(Console.ReadLine());
                }
                else
                {
                    matrix[i, j] = 0;
                }
            }
        }

        // Display the upper triangular matrix
        Console.WriteLine("\nUpper Triangular Matrix:");
        for (int i = 0; i < size; i++)
        {
            for (int j = 0; j < size; j++)
            {
                Console.Write(matrix[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
}

How It Works:

  1. The program starts by asking the user to input the size of the matrix (number of rows and columns).
  2. It then creates a 2D array to store the matrix.
  3. Next, the program asks the user to input the elements of the matrix row by row, but it only accepts input for elements in the upper triangular part (where the column index is greater than or equal to the row index).
  4. For elements in the lower triangular part, the program sets them to zero.
  5. Finally, the program displays the upper triangular matrix.

Input/Output:

Share:

Leave A Reply

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

You May Also Like

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...
This C# program demonstrates how to calculate the transpose of a matrix. The transpose of a matrix is a new...