write a program to find solution of linear equation using Gauss-Seidel method in c++.

write a program to find solution of linear equation using Gauss-Seidel method in c++.
Source Code:
/*************************************
    language: C
    Author : Tanveer Khan
    Rajasthan University, Jaipur
************************************************/
  1. #include<iostream>
  2. #include<conio.h>
  3.  
  4. using namespace std;
  5.  
  6. int main(void)
  7. {
  8.     float a[10][10], b[10], x[10], y[10];
  9.     int n = 0, m = 0, i = 0, j = 0;
  10.     cout << "Enter size of 2d array(Square matrix) : ";
  11.     cin >> n;
  12.     for (i = 0; i < n; i++)
  13.     {
  14.         for (j = 0; j < n; j++)
  15.         {
  16.             cout << "Enter values no :(" << i << ", " << j << ") ";
  17.             cin >> a[i][j];
  18.         }
  19.     }
  20.     cout << "\nEnter Values to the right side of equation\n";
  21.     for (i = 0; i < n; i++)
  22.     {
  23.         cout << "Enter values no :(" << i << ", " << j << ") ";
  24.         cin >> b[i];
  25.     }
  26.     cout << "Enter initial values of x\n";
  27.     for (i = 0; i < n; i++)
  28.     {
  29.         cout << "Enter values no. :(" << i<<"):";
  30.         cin >> x[i];
  31.     }
  32.     cout << "\nEnter the no. of iteration : ";
  33.     cin >> m;
  34.     while (m > 0)
  35.     {
  36.         for (i = 0; i < n; i++)
  37.         {
  38.             y[i] = (b[i] / a[i][i]);
  39.             for (j = 0; j < n; j++)
  40.             {
  41.                 if (j == i)
  42.                     continue;
  43.                 y[i] = y[i] - ((a[i][j] / a[i][i]) * x[j]);
  44.                 x[i] = y[i];
  45.             }
  46.             printf("x%d = %f    ", i + 1, y[i]);
  47.         }
  48.         cout << "\n";
  49.         m--;
  50.     }
  51.     return 0;
  52. }
OUTPUT
$ g++ GaussSeidel.cpp
$ a.out
 
Enter size of 2d array(Square matrix) : 3
Enter values no :(0, 0) 2
Enter values no :(0, 1) 3
Enter values no :(0, 2) 1
Enter values no :(1, 0) 5
Enter values no :(1, 1) 4
Enter values no :(1, 2) 6
Enter values no :(2, 0) 8
Enter values no :(2, 1) 7
Enter values no :(2, 2) 9
 
Enter Values to the right side of equation
Enter values no :(0, 3) 2
Enter values no :(1, 3) 3
Enter values no :(2, 3) 4
 
Enter initial values of x
Enter values no. :(0): 0
Enter values no. :(1): 0
Enter values no. :(2): 0
 
Enter the no. of iteration : 4
x1 = 1.000000    x2 = -0.500000    x3 = -0.055556    
x1 = 1.777778    x2 = -1.388889    x3 = -0.055556    
x1 = 3.111111    x2 = -3.055555    x3 = 0.055555    
x1 = 5.555555    x2 = -6.277777    x3 = 0.388889

Comments

Popular Posts