The Program in C++ Program to Check Whether a given number is Perfect or not is given below:
#include <iostream>
using namespace std;
int main() {
int num, i, sum = 0;
cout << "Hello Codeauri Family,enter a Perfect Number here: ";
cin >> num;
for (i = 1; i <= num/2; i++) {
if (num % i == 0) {
sum += i;
}
}
if (sum == num) {
cout << num << " is a perfect number." << endl;
} else {
cout << num << " is not a perfect number." << endl;
}
return 0;
}
Output:
Hello Codeauri Family,enter a Perfect Number here: 28
28 is a perfect number.
Pro-Tips💡
The main
function is the entry point of the program.
Here we declare three variables: num
to store the user’s input, i
to use as a loop variable, and sum
to store the sum of the divisors of num
.
We then prompt the user to enter a positive integer and store it in num
This for loop runs i
from 1 to num/2
, checking if i
is a divisor of num
by using the modulus operator %
. If i
is a divisor of num
, we add it to sum
.
Finally, after the loop, we check if sum
is equal to num
. If it is, num
is a perfect number and we print a message saying so.
If sum
is not equal to num
, num
is not a perfect number and we print a message saying so.
The return 0;
statement at the end of the main
function returns 0 to indicate that the program has executed successfully.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.