Input number and check perfect number or not using while loop in C++
while Loop - Question 8
In this question, we will see how to input a number and check if it is a perfect number or not in C++ programming using while loop. To know more about while loop click on the while loop lesson.
Q8) Write a program in C++ to input a number and check if it is a perfect number or not using while loop.
A Perfect number is a number, whose sum of the factors excluding the given number itself is equal to the given number.
Example: Sum of factors of 6 excluding 6 is 1+2+3 which is equal to 6, so 6 is a perfect number.
Program
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int i=1,n,sf=0;
cout<<"Enter a number ";
cin>>n;
while(i<n)
{
if(n%i==0)
{
sf=sf+i; // sum of factors
}
i=i+1;
}
if(sf==n)
{
cout<<"Perfect Number";
}
else
{
cout<<"Not Perfect Number";
}
return 0;
}
Output
Enter a number 28 Perfect Number