Weird do-while loop error

I am doing a Pythagorean triples program where it detects how many triples there are based on the upper limit that's inputted. So, when I first execute the loop, and it goes through one iteration, it runs fine. But when I input a y or Y for the while loop to redo it, and put in a new upper limit, it doesn't run like the first time. White space is all over the place and the number of triples it shows is off. I need it to run like the first time it iterates, what am I missing so it stays consistent?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;

int main() {
	int upperLimits;
	int totalTriples = 0;
	int i, j, k;
	char option;

	do {
		cout << "Enter the upper limits for the sides of the right triangle: ";
		cin >> upperLimits;
		cout << "Side 1  Side 2  Side3" << endl;

		for (i = 0; i < upperLimits; i++) {

			for (j = i + 1; j < upperLimits; j++) {

				for (k = j + 1; k <= upperLimits; k++) {

					if (pow(i, 2) + pow(j, 2) == pow(k, 2)) {
						cout << i << setw(8);
						cout << j << setw(8);
						cout << k << setw(8) << left << endl;
						totalTriples++;
					}
				}
			}
		}
		cout << "A total of " << totalTriples << " triples were found." << endl;
		cout << "Y or y continue, anything else quits" << endl;
		cin >> option;
	} while (option == 'y' || option == 'Y');

	return 0;
}
Last edited on
You never reset the value of totalTriples inside the loop so it will just continue counting from where the last iteration left off.

Note that std::setw and std::left affects whatever output comes after. std::left doesn't go away automatically so if you want to restore right-alignment after you have used std::left you need to use std::right.
Thank you I got it. Alignment is still pretty new to me. Should try to practice it more.
Topic archived. No new replies allowed.