0
Triple For Loop
I must use a triple for loop to display all the possible pythagorean triples by using the brute force method. My program just prints 2 for what seems like an infinity. #include <iostream> using namespace std; int main() { int count = 0; int side; cout << "Side 1\tSide 2\tHypotenuse" << endl; for (int side1 = 1; side1 <= 500; side1++){ cout << side1; for (int side2 = side1; side2 <= 500; side2++){ cout << side2; for (int hypotenuse = side2; hypotenuse <= 500; hypotenuse++){ hypotenuse = (side1 * side1) + (side2 * side2); cout << hypotenuse; } } } cout << "A total of " << count << " triples were found." << endl; system("pause"); return 0; }
3 Answers
+ 8
#include <iostream>
using namespace std;
int main()
{
int count = 0;
int side;
cout << "Side 1\t\t Side 2\t\t Hypotenuse" << endl;
for(int side1 = 1; side1 <= 10; side1++)
{
for(int side2 = side1; side2 <= 10; side2++)
{
for(int hypotenuse = side2; hypotenuse <= 10; hypotenuse++)
{
side = (side1 * side1) + (side2 * side2);
cout << side1 << string(10, ' ') << side2 << string(10, ' ') << side << endl;
}
}
}
cout << "A total of " << count << " triples were found." << endl;
return 0;
}
Well actually inside the inner most for loop you are changing the value of hypotenuse variable, that's why loop was infinite.
I changed the hypotenuse variables with side variable which was unused.
Also I changed the 500 to 10 in each for loop for testing purpose, you can change it back to 500 it will work fine.
+ 8
It prints a character n times.
In line string(10, ' ');
It prints 10 spaces
0
Can you please explain what the string(10, '') is?