How to break out of a loop in C

user2059456 picture user2059456 · Feb 14, 2013 · Viewed 17.9k times · Source

I'm writing a bisection method algorithm to find the roots of polynomials. The second part of my code where it says if variable FP is equal to zero or absolute value of b-a it just breaks the if statement I guess.

I want the program to stop the for loop (iteration) entirely and return p. And at the end I want to print the number of iteration it took to get the solution but apparently using my printf statement it shows that the program keeps executing even thought the root (zero) is obtained.

Any ideas on how to stop the whole mechanism and return both the value of p which is zero and the exact number of iteration it took? Thanks

double computeroots(double a, double b, double epsilon, int MaxIter)
{
    double FA = pow(a,4) -4*a +  1;
    double FB = pow(b,4) - 4*b + 1;
    double FP;
    double p;
    int i;

    for(i=0;i<MaxIter;i++) {
        if(FA * FB < 0) {
            p = a + (b-a)/2;
            FP = pow(p,4) - 4*p +1;
            if(FP == 0 || abs(b-a) < epsilon) {
                return p;
                break;
            } else if (FA * FP >0) {
                a =p;
                FA = FP;
            } else {
                b = p;
                FB = FP;
            }
            i++;
        }
    }

    printf("The number of iterations is: %d\n", i);
}

Answer

ecatmur picture ecatmur · Feb 14, 2013

Your printf statement isn't hit because you have a return p; before the break statement. A return statement immediately exits the function.

You need to move the return statement to after the printf, or move the printf before the return:

        if(FP == 0 || abs(b-a) < epsilon)
        {
            printf("the number of iterations is : %d\n", i);
            return p;
        }
        ...

    printf("failed to converge after %d iterations\n", i);
    return p;
}