Re: breaking out of a loop
Quote:
Originally Posted by
FeralDruidonWoW
hello. i am writing a program that prints all pythagorean triplets (ex. 3^2 + 4^2 = 5^2) until a + b + c = 1000. My code does that but keeps running after it finds that combination.
The simplest solution is to just introduce a boolean, and put the value of that boolean in the loop condition:
Code:
bool foundMyNumbers = false;
for(a = 1; a < 1000 && !foundMyNumbers; a++)
{
for(b = 1; b < 1000 && !foundMyNumbers; b++)
//....
// etc...
//...
if ( I hit the magic combination )
foundMyNumbers = true;
//...
}
//...
}
Regards,
Paul McKenzie
Re: breaking out of a loop
Excellent! thanks for the advice. Program terminates as expected now :)
Re: breaking out of a loop
Quote:
Originally Posted by
FeralDruidonWoW
Excellent! thanks for the advice. Program terminates as expected now :)
In this particular case, all that was required of you was to explicitly return from main when a + b + c == 1000.
If your ultimate goal is to find the triplet that satisfies the condition outlined above then you're doing a little too much work.
The following is my solution from a while back to the same problem in C99:
Code:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
for(uint32_t a = 1;; ++a)
{
for(uint32_t b = 999; b > a; --b)
{
const uint32_t c = 1000 - a - b;
if((a * a) + (b * b) == (c * c))
{
printf("%u\n", (a * b * c));
fflush(stdout);
return EXIT_SUCCESS;
}
}
}
}