# C++ Program to Check perfect number

January 31, 2023, Learn eTutorial
1092

This is a C++ program to check whether a number entered by the user is a perfect number or not.

## Which Number can be called a Perfect Number?

If a number is equal to the sum of its positive divisors (excluding the number itself), then that number can be called a perfect number. For example, 28 is a perfect number, because the divisors of 28, in this case, are 1, 2, 4, 7, and 14. And the sum of all these divisors gives the original number itself. That is:

28 = 1+2+4+7+14
= 14+14
= 28
Therefore 28 is a perfect number.

## How to write a C++ program to check for a perfect number?

Ask the user to enter a number and read the number into the variable num. Here we are using for loop to check for a perfect number After the number get stored in the variable num, start the execution of for loop with initialization i= 1 and condition i < num and updation i++; Within the` for loop` an `if condition `statement is used to get the divisors of the number.

The number is divided and checked for the remainder is zero, to check whether i is a positive divisor of the number using mod operator.

if(num%i==0)

If the condition evaluates true then a variable sum initially set as 0 is updated its value by adding i to itself. The value of i is incrementing by 1 for each iteration. The procedure continues until the condition of `for loop` i < num gets false. After exiting the loop the variable sum holds the sum of all positive divisors of the number. Now we have to compare the value of the sum with the number itself using an` if-else` statement.

Here if the condition num = = sum is true then print the number is a perfect number, else print the number is not a perfect number.

### Algorithm

Step 1: Call the header file `iostream.`

Step 2: Use the `namespace std.`

Step 3: Open the main function; int main().

Step 4: Declare  integer type variables num, i, and sum = 0;

Step 5: Ask the user to enter a number.

Step 6: Get the number to the variable num;

Step 9: Define a `for loop` with i =1 and check for the condition i< num; update the value of i for each iteration by 1;

within the loop divide the number by i and check for the remainder.

If the remainder is 0; then add i to the sum

Step 10: Check if the number is equal to the sum then print the perfect number

Step 11: else print is not perfect

Step 12: exit

## C++ Source Code

```                                          ```#include<iostream>

using namespace std;
int main()
{
int num, i, sum=0;
cout<<"Enter a Number: ";
cin>>num;
for(i=1; i<num; i++)
{
if(num%i==0)
sum = sum+i;
}
if(num==sum)
cout<<endl<<num<<" is a Perfect Number.";
else
cout<<endl<<num<<" is not a Perfect Number.";
cout<<endl;
return 0;
}```
```

## OUTPUT

```Run 1
Enter a Number: 78
78 is not a Perfect Number.
Run 2
Enter a Number: 496
496 is a Perfect Number.
```

VIEW ALL
VIEW ALL