printing "no solution" when the value is not in the loop.

what i am trying to do is to print no solution if the value of x and y is not there. but it is printing no solution in loops even if the the value of x and y exists.
for example if i enter 271, the x is 5 and y is 7 and then loop should end but it keeps on going on print no solution as well.

THANK YOU VERY MUCH IN ADVANCE!!

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
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
	int x, y, n;
	cout << "Enter the positive integer" << endl;
	cin >> n;
	

	for (x = 10; x > 0; x--) {
		for (y = 0; y < 10; y++)
			if (3 * pow(x, 2) + 4 * pow(y, 2) == n) {

				cout << "3x^2 + 4y^2 = "<<n<<" has a solution " << endl << "x value is : " << x << endl << "y value is: " << y << endl;

			}
		
			else {
				cout << "no sol" << endl;
				
			}
		
	}
	
	

	system("pause");
	return 0;
}
Last edited on
Hello soby96,

I would try at line 18 adding:
1
2
x = 0;
break;


And see what happens. The break will end the inner for loop and setting x equal to 0 should end the outer for loop.

Hope that helps,

Andy
Hi Andy, thanks for replying.

it is still print no solution in multiple loops. i want it t print "no solution" once if the values are not there. and not to print " no solution if the value is there.
I am using 271 as the value of n. x is 5 and y is 7.
Hi,

You can use a bool flag which gets true if your condition matches and then print accordingly outside the loop...
Hello soby96,

I have not loaded your program yet, but the bit of code I showed you earlier should also work in the else block.

At this time of night I wil have to work on it in the morning.

Andy
Hello soby96,

It finally hit me this morning: else if(x==1 && y==9). This only lets "no solution" print just once if needed.

Hope that helps,

Andy
Last edited on
It's better to declare variables only when you really need them.

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
#include <cmath>
#include <iostream>

int main()
{
    std::cout << "Enter the positive integer: ";
    int n;
    std::cin >> n;

    bool found = false;
    for (int x = 10; x > 0; x--) {
        for (int y = 0; y < 10; y++) {
            if (3 * std::pow(x, 2) + 4 * std::pow(y, 2) == n) {
                std::cout << "3x^2 + 4y^2 = " << n << " has a solution\n"
                             "x value is : " << x << "\ny value is: " << y << '\n';
                found = true;
                break;
            }
            if(found) { break; }
        }
    }
    if(!found) { std::cout << "no solution.\n"; }
    system("pause"); // <-- avoid this: http://www.cplusplus.com/forum/beginner/1988/
    return 0;
}

Topic archived. No new replies allowed.