Ending a program with while loop

Hi I am struggling to make this program repeat until the user types -1. Does anyone know how I can do it with a while loop and break when the user enters -1 because right now it only takes 1 number and ends.

#include <iostream>
using namespace std;

bool isPerfect(int number)
{
int i = 0;
int sum = 0;

while (i++ < number)
{
if (number % i == 0 && i < number)
{
sum += i;
}
}

return sum == number;
}

int main()
{
int n, int countPerfect; #counting perfect numbers

cout << "Enter a number (-1 to quit): " << endl;
cin >> n;

if (isPerfect(n))
{
cout << "It is a perfect number" << endl;
}
else
{
cout << "It is not a perfect number" << endl;
}

return 0;
}
Last edited on
1
2
3
while( std::cin >> number and number not_eq -1 ){
   //...
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

bool isPerfect(int number) {
	int sum {};

	for (int i {1}; i < number; ++i)
		if (number % i == 0 && i < number)
			sum += i;

	return sum == number;
}

int main() {
	for (int n {}; (std::cout << "Enter a number (-1 to quit): ") && (std::cin >> n) && (n != -1); )
		if (isPerfect(n))
			std::cout << "It is a perfect number\n";
		else
			std::cout << "It is not a perfect number\n";

}

Topic archived. No new replies allowed.