I'm having difficulty breaking out of this nested loop. This is a function for reducing a fraction. Normally original_num and original_denom will be numbers that are reducible and z will normally be the GCD. Sometimes like in this particular that you see here 37 and 51 are not reducible. The only two ways I know of to break out of a loop is with a break statement or return 0, but in this case neither will work. I have a void statement so can't use a return statement and its a nested loop so I can't use a break statement.

void reduce(int original_num, int original_denom, int *reduced_num, int *reduced_denom)
{
    int z = 1;
    int a = 0;
    int b = 0;
    int original_num = 37;
    int original_denom = 51;
    //int i = 0;
    a = original_num;
    b = original_denom;
	
	//z = gcd(original_num , original_denom);
	printf("The value of z is %d\n", z);
    
    while(a / z != 0)
    {
        if((a / z) != 0)
        {
            a /= z;
		}
		else if(a / z == a)
		{
			break;
		}
    }
    while(b / z != 0)
	{
		if((b / z) != 0)
		{
			b /= z;
		}
        else if(b / z == b)
		{
		    break;
		}
    }

    *reduced_num = a;
    *reduced_denom = b;
}

Recommended Answers

All 5 Replies

The only two ways I know of to break out of a loop is with a break statement or return 0, but in this case neither will work. I have a void statement so can't use a return statement

You can use a return from a void function.

and its a nested loop so I can't use a break statement.

Which loop do you see as nested?

You can use a return from a void function.


Which loop do you see as nested?

In unix it gives you a warning. I'm not allowed to have warnings.

As for part 2.
The if loop is nested in the while loop.

What DS means is don't try to return a value, just have a return; statement where you need it. If is not a loop anyhow. What is the specific warning you are getting?

It is called an if statement, not an if loop. Only structures which repeat are called loops, such as for loops, do while loops, and while loops. If you can't use a return; or a break; statement, you could simply have a boolean variable (actually an int in C) and set it to "1". Before entering any loops or doing anything substantial, check to see if it is "1", and if so, don't do anything. This will have the effect of returning from the function.

You could use exit as well.
But for this situation it is more appropriate to use the suggestions mentioned above

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.