-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLinearSystemSolver.cs
More file actions
106 lines (93 loc) · 3.41 KB
/
LinearSystemSolver.cs
File metadata and controls
106 lines (93 loc) · 3.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System;
class LinearSystemSolver
{
static void Main(string[] args)
{
Console.WriteLine("Linear System Solver - Task Assignment");
Console.WriteLine("Second Level - First Semester: 2023-2024\n");
Console.WriteLine("Name: Amr Bedir Taher");
Console.WriteLine("ID: 1000264365");
Console.WriteLine("Group: 2, Section: 12");
Console.WriteLine("\n____________________\n");
Console.Write("Enter the number of equations: ");
int n = int.Parse(Console.ReadLine());
// Create a matrix to store the coefficients and constants of the linear system
double[,] matrix = new double[n, n + 1];
// Input coefficients and constants for each equation
for (int i = 0; i < n; i++)
{
Console.WriteLine($"Enter coefficients for equation {i + 1}:");
for (int j = 0; j < n; j++)
{
Console.Write($"a{i + 1}{j + 1}: ");
matrix[i, j] = double.Parse(Console.ReadLine());
}
Console.Write($"Enter the constant (b{i + 1}): ");
matrix[i, n] = double.Parse(Console.ReadLine());
}
// Perform Gaussian elimination to convert the matrix into upper triangular form
for (int k = 0; k < n; k++)
{
for (int i = k + 1; i < n; i++)
{
double factor = matrix[i, k] / matrix[k, k];
for (int j = k; j <= n; j++)
{
matrix[i, j] -= factor * matrix[k, j];
}
}
}
// Backward substitution to find the solution with row swapping
double[] solution = new double[n];
for (int i = n - 1; i >= 0; i--)
{
// Check if the coefficient is zero and swap rows if needed
if (matrix[i, i] == 0)
{
for (int m = i - 1; m >= 0; m--)
{
if (matrix[m, i] != 0)
{
// Swap rows i and m
for (int j = 0; j <= n; j++)
{
double temp = matrix[i, j];
matrix[i, j] = matrix[m, j];
matrix[m, j] = temp;
}
break;
}
}
}
// Continue with the backward substitution
solution[i] = matrix[i, n];
for (int j = i + 1; j < n; j++)
{
solution[i] -= matrix[i, j] * solution[j];
}
solution[i] /= matrix[i, i];
}
// Display the solution with steps
Console.WriteLine("\n____________________\n");
Console.WriteLine("Solution with Steps:");
for (int i = 0; i < n; i++)
{
Console.Write($"x{i + 1} = ({matrix[i, n] / matrix[i, i]:0.00})");
for (int j = 0; j < n; j++)
{
if (j != i)
{
Console.Write($" - ({matrix[i, j]:0.00} * x{j + 1})");
}
}
Console.WriteLine();
}
// Display the final solution
Console.WriteLine("\n____________________\n");
Console.WriteLine("Final Solution:");
for (int i = 0; i < n; i++)
{
Console.WriteLine($"x{i + 1} = {solution[i]:0.00}");
}
}
}