The Program in C# Program to Create an Identity Matrix is given below:
using System;
namespace IdentityMatrix
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Codeauri Family, enter the size of the identity matrix :");
int size = int.Parse(Console.ReadLine());
int[,] matrix = CreateIdentityMatrix(size);
PrintMatrix(matrix);
}
static int[,] CreateIdentityMatrix(int size)
{
int[,] matrix = new int[size, size];
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (i == j)
{
matrix[i, j] = 1;
}
else
{
matrix[i, j] = 0;
}
}
}
return matrix;
}
static void PrintMatrix(int[,] matrix)
{
int size = matrix.GetLength(0);
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
Output:
Hello Codeauri Family, enter the size of the identity matrix :
1 0 0
0 1 0
0 0 1
Pro-Tips💡
Here are the step by step execution of above program:
- The
using System
directive at the top of the file includes theSystem
namespace in the program, which provides access to various system-level functions, including theConsole
class used in this code. - The code defines a namespace
IdentityMatrix
that encapsulates all of the code in the program. - The
Program
class contains the program’s main method,Main
, which is the entry point of the program. - In the
Main
method, the program prompts the user to enter the size of the identity matrix by writing a message to the console. The size is then read from the console and stored in thesize
variable. - The
CreateIdentityMatrix
method is then called with thesize
parameter. This method returns an identity matrix of the specified size, which is stored in thematrix
variable. - The
PrintMatrix
method is then called with thematrix
parameter, which prints the contents of the matrix to the console, row by row. - The
CreateIdentityMatrix
method initializes a two-dimensional integer arraymatrix
of the specified size and sets the diagonal elements to 1 and the rest to 0. This is done by using nested for loops to iterate over the rows and columns of the array. If the row and column indices are equal (i == j
), the current element is set to 1, otherwise it is set to 0. - The
PrintMatrix
method prints the contents of the matrix to the console, row by row. This is done by using nested for loops to iterate over the rows and columns of the matrix and printing the elements, separated by a space. After each row is printed, a line break is added to separate the rows.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.