C++ string help_for loop issues

I am trying to implement the gauss seidel algorithim in C++. I will provide a working example so you can understand what im trying to do and how i need to set up the syntax so it can do that.

a + b = 5
a + 2b = 8

therefore the matrix would be:

[1 1 5]
[1 2 8]

Assume that the starting value of a and b is 0 and keep iterating until the answer the solution converges to the real answer for example:

a + 1*(0) = 5 => a = 5
1*(5) + 2*b = 8 => b = 1.5
a + 1*1.5 = 5 => a = 3.5
1*(3.5) + 2*b = 8 => b = 2.25
a + 1*(2.25) = 5 +> a = 2.75....

if you keep iterating this you will eventually arive to the answer b = 3 a = 2, (try it in excel if you would like)

now im trying to do this with a for loop so yes I want row and col1 to keep resetting to 0 but only the marker not the actual value inside of the array. So basically after each for loop I want the array elements to save their values and keep reassigning new values to value[row][col1] after each iteration thus converging closer and closer to the answer as you saw in the example i just showed. My code is below but it keeps outputting 5 4 regardless of what condition I set for i:

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
#include <iostream>

using namespace std;

int main()
{
   int row, col, col1,i;
   float array[2][3];
     float value[2][3];
     float x[2][3];

     // construct matrix system
     array[0][0]= 1;
     array[0][1]= 1;
     array[0][2]= 5;
     array[1][0]= 1;
     array[1][1]= 2;
     array[1][2]= 8;
     value[0][2] = 5;
     value[1][2] = 8;



// solve the system of equations a+b = 5, a + 2b = 8
    for(i = 0; i<20; i++)
    {
    row = 0;
    col1 =0;
    col = 2;
    value[row][col1] = (value[row][col] - value[row][col1+1]*array[row][col+1])/array[row][col1];
    row++;
    col1++;
    value[row][col1] = (value[row][col] - value[row][col1-1]*array[row][col-1])/array[row][col1];
    }
    cout<< value[0][0];
    cout<< value[1][1];
    cin.get();
}


The process is rather simple, but it hurts me so much your variable names. I can't figure out their purpose from their names. Rename them to be more meaningful. In the meantime, I ask:

1. What is the array value for?
2. What is the array x for?
3. Why do you initialize the last column of the value array? (Although this may become clear once you answer #1).

Now what I think is needed:
You just need the array X to be X[2]:
1
2
3
4
for (int row = 0; row < 2; row++)
{
    X[row] = (array[row][2] - array[row][(row + 1) % 2] * X[(row + 1) % 2]) / array[row][row];
}


I did not test the above, but I think it works. X[0] would be a and X[1] would be b. You run that for loop inside your big for loop and you get your estimation.
Last edited on
Topic archived. No new replies allowed.