Search code examples
c#loopscurvedo-while

What's Wrong in this Looping Code


Here is the problem:

Constants: 'a', 'b', 'c', 'd';

I have a lot of variables, but only these are interconnected: 'x', 'y', 'z';

For first iteration 1 have:

x1 = [value from other variables];
y1 = x1 + a;
z1 = y1 + x1 + b;
condition |c - z1| < d;

If it is true, then the program calculates the other elements (from this point I know the job), but if the condition is false we have something like this:

x2 = x1 + e;
y2 = x2 + a;
z2 = y2 + x2 + b;
condition |c - z2| < d; 

Again, if false:

x3 = x2 + e;
y3 = x3 + a;
z3 = y3 + x3 + b;
condition |c - z3| < d; 

and so on until the condition is met.

What I'am trying to solve is a loop to extract from the last iteration (i) the values of 'xi' and 'yi' to use in later development. I can't extract them unless the condition is met.

Thank you.


Solution

  • You can use a while loop:

    var x = // value from other variables
    var y = x + a;
    var z = y + x + b;
    
    while (Math.Abs(c - z) < d)
    {
        x = x + e;
        y = x + a;
        z = y + x + b;
    }