-3

This program solves linear system of equations by using Gauss-Siedel iterative process, where the initial approximation is: (x0, y0, z0) = (0, 0, 0)

But when I am running it the window shuts immediately after I enter the matrix input and can't complete the whole program.

Here is the code:

#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;

int main(){
    float x1, x2, x3, x1new, x2new, x3new, sum;
    float a[3][3], b[3], error[3];
    x1 = x2 = x3 = 0;
    x1new = x2new = x3new = 0;

    cout <<"enter the coefficients of equation or matrix a \n";
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++)
            cin >> a[i][j];
    }
    cout <<" \n enter the right side values of equation or matrix b ";
    for(int i = 0; i < 3; i++)
        cin >> b[i];

    for(int i = 0; i < 3; i++){
        error[i] = 1;
    }

    while((error[0]| | error[1]| | error[2]) > =0.00001){
        x1 = (b[0] - (a[0][1] * x2 + a[0][2] * x3)) / a[0][0];
        x2 = (b[1] - (a[1][0] * x1 + a[1][2] * x3)) / a[1][1];
        x3 = (b[2] - (a[2][0] * x1 + a[2][1] * x2)) / a[2][2];
        error[0] = abs(x1) - abs(x1new);
        error[1] = abs(x2) - abs(x2new);
        error[2] = abs(x3) - abs(x3new);
        x1new = x1;
        x2new = x2;
        x3new = x3;
    }
    cout <<"\n the values of variables x1,x2 and x3 are:";
    cout << x1 << x2 << x3;
}

Question:

What am I doing wrong?

ritu
  • 1
  • 1
  • [4 -1 1;4 -8 1;-2 1 5] [7 -21 15] – ritu Sep 24 '15 at 11:19
  • You've edited the post, but I still see references to subscript 3 as in b[3], when the array is allocated for only 3 elements. THAT will crash the program. There is no data in b[3], even if you expand the allocation to float b[4] (3 is the 4th element in b), you still PUT nothing in b[3]. Same for a[3]. Should those NOT index from 0 to 2, like all else, or do you think it should index from 1 to 3? – JVene Sep 24 '15 at 17:39

1 Answers1

1

Given:

float a[3][3],b[3],error[3];

The obvious problem is:

x1=(b[1]-(a[1][2]*x2+a[1][3]*x3))/a[1][1];
x2=(b[2]-(a[2][1]*x1+a[2][3]*x3))/a[2][2];
x3=(b[3]-(a[3][1]*x1+a[3][2]*x2))/a[3][3];

Where all indexes of 3 reference a 4th index, which is not allocated.

That causes a segfault on Linux, an access violation in Windows.

The overall view of this code suggests the indices are thought to begin at 1, when in fact they begin at zero.

Consider changing that to:

x1=(b[0]-(a[0][1]*x2+a[0][2]*x3))/a[0][0];
x2=(b[1]-(a[1][0]*x1+a[1][2]*x3))/a[1][1];
x3=(b[2]-(a[2][0]*x1+a[2][1]*x2))/a[2][2];
JVene
  • 1,611
  • 10
  • 10
  • thanks a lot :) i have correct my mistake but still not able to find the solution – ritu Sep 24 '15 at 12:04
  • @ritz Welcome to SO! The preferred way of expressing gratitude towards the author of the valuable information that has helped you here is by **up-voting** or **accepting** the given answer. In your case only the latter applies, till you reach 15 reputation. – Ziezi Sep 24 '15 at 12:24