Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please assist: "if" statement in C++

The following code prints the same result - twice (!) (using Microsoft Visual C++ 2010 IDE). I also printed the final values of each variable to see what was going on and there are in effect two sets of values that satisfy the if statement condition.

My question is since the instruction was break; if the condition evaluated TRUE, can anyone kindly explain how/why I am getting both results when I didn't ask for that (not that it's a bad thing, just trying to understand) ? Is this part of the if construct or does it have something to do with the loops ? It seems as though something knows to return multiple solutions if the condition evaluates to TRUE more than once, I just don't get how it's able to do that when the instructions don't explicitly say to do that (unless there is something built-in that I don't know of).

Basically, why doesn't the loop end at break; once the condition is met or am I thinking about this the wrong way ?

Again, if anyone knows or if I am missing something basic here please let me know ! I'm new to C++ so just trying to learn, thank you in advance.

Here is the code:

#include "stdafx.h"
#include <iostream>     

int main()
{
    for (int a = 1; a < 500; ++a)
    {
        for (int b = 1; b < 500; ++b)
        {
            for (int c = 1; c < 500; ++c)
            {
                if ((a + b + c) == 1000 && ((a*a + b*b) == (c*c)))
                {
                 cout << "The product abc = " << a*b*c << endl << "a = " << a << ", b = " << b << ", c = " << c << endl;
                 break;
                }
            }
        }
    }
    cout << endl << "Loop terminated";

    char d;
    cin >> d;
    return 0;
}

The console output is the following:

The product abc = 31875000

a = 200, b = 375, c = 425

The product abc = 31875000

a = 375, b = 200, c = 425

Loop terminated

like image 273
montecarlo76 Avatar asked Dec 17 '25 04:12

montecarlo76


1 Answers

Your break only breaks out of the inner loop, so the outer loop continues to execute.

One possibility would be to move that code into a separate function, and return from the function when you find the match the first time. Then (unless you call the function again) execution of that code will cease completely.

I'd also eliminate the loop for c entirely. The only meaningful value for c is 1000 - (a+b), so you might as well just compute it directly instead of looping through 500 different values to find it.

like image 101
Jerry Coffin Avatar answered Dec 19 '25 17:12

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!