This is a C++ Program to Check if a Number is a Perfect Number.
The program intakes a number and checks if it is a perfect number or not. A perfect number is equal to the sum of its divisors excluding itself.
1. The number to be checked if it is perfect or not is entered.
2. The divisors of the number are calculated and added.
3. If the sum of the divisors is equal to the original number, then it is a perfect number.
4. Else the given number is not a perfect number,
5. The result is printed.
6. Exit.
Here is the source code of C++ Program to Check if a Number is a Perfect Number. The program output is shown below.
#include<iostream>
using namespace std;
int main ()
{
int i, num, div, sum=0;
cout << "Enter the number to be checked : ";
cin >> num;
for (i=1; i < num; i++)
{
div = num % i;
if (div == 0)
sum = sum + i;
}
if (sum == num)
cout << "\n" << num <<" is a perfect number.";
else
cout << "\n" << num <<" is not a perfect number.";
return 0;
}
1. The user is asked to enter the number to be checked and it is stored in the variable ‘num’.
2. Initialize the variable ‘sum’ as 0.
3. A ‘for’ loop is used to find the factors of the given number.
4. Using the modulus operator, the divisors are calculated.
5. If the remainder is 0, it is added to the variable ‘sum’.
6. The loop continues till it reaches num-1.
7. Now, if ‘sum’ equals the entered number ‘num’, then it is a perfect number.
8. Else the entered number is not a perfect number.
9. The result is then printed.
Case 1 : Enter the number to be checked : 28 28 is a perfect number. Case 2 : Enter the number to be checked : 16 16 is not a perfect number. Case 3 : Enter the number to be checked : 6 6 is a perfect number.
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.
- Practice Programming MCQs
- Apply for C++ Internship
- Check Computer Science Books
- Apply for Computer Science Internship
- Practice Computer Science MCQs