Algorithms_in_C++  1.0.0
Set of algorithms implemented in C++.
gaussian_elimination.cpp File Reference

Gaussian elimination method More...

#include <iostream>
Include dependency graph for gaussian_elimination.cpp:

Functions

int main ()
 

Detailed Description

Function Documentation

◆ main()

int main ( void  )

Main function

9  {
10  int mat_size, i, j, step;
11 
12  std::cout << "Matrix size: ";
13  std::cin >> mat_size;
14 
15  // create a 2D matrix by dynamic memory allocation
16  double **mat = new double *[mat_size + 1], **x = new double *[mat_size];
17  for (i = 0; i <= mat_size; i++) {
18  mat[i] = new double[mat_size + 1];
19  if (i < mat_size)
20  x[i] = new double[mat_size + 1];
21  }
22 
23  // get the matrix elements from user
24  std::cout << std::endl << "Enter value of the matrix: " << std::endl;
25  for (i = 0; i < mat_size; i++) {
26  for (j = 0; j <= mat_size; j++) {
27  std::cin >>
28  mat[i][j]; // Enter (mat_size*mat_size) value of the matrix.
29  }
30  }
31 
32  // perform Gaussian elimination
33  for (step = 0; step < mat_size - 1; step++) {
34  for (i = step; i < mat_size - 1; i++) {
35  double a = (mat[i + 1][step] / mat[step][step]);
36 
37  for (j = step; j <= mat_size; j++)
38  mat[i + 1][j] = mat[i + 1][j] - (a * mat[step][j]);
39  }
40  }
41 
43  << "Matrix using Gaussian Elimination method: " << std::endl;
44  for (i = 0; i < mat_size; i++) {
45  for (j = 0; j <= mat_size; j++) {
46  x[i][j] = mat[i][j];
47  std::cout << mat[i][j] << " ";
48  }
50  }
52  << "Value of the Gaussian Elimination method: " << std::endl;
53  for (i = mat_size - 1; i >= 0; i--) {
54  double sum = 0;
55  for (j = mat_size - 1; j > i; j--) {
56  x[i][j] = x[j][j] * x[i][j];
57  sum = x[i][j] + sum;
58  }
59  if (x[i][i] == 0)
60  x[i][i] = 0;
61  else
62  x[i][i] = (x[i][mat_size] - sum) / (x[i][i]);
63 
64  std::cout << "x" << i << "= " << x[i][i] << std::endl;
65  }
66 
67  for (i = 0; i <= mat_size; i++) {
68  delete[] mat[i];
69  if (i < mat_size)
70  delete[] x[i];
71  }
72  delete[] mat;
73  delete[] x;
74 
75  return 0;
76 }
Here is the call graph for this function:
mat_size
ll mat_size
Definition: matrix_exponentiation.cpp:45
std::cout
std::endl
T endl(T... args)
std::cin
machine_learning::sum
T sum(const std::vector< std::valarray< T >> &A)
Definition: vector_ops.hpp:232