ADVERTISEMENT
Check Perfect Number or Not
#include<stdio.h>
#include<math.h>
main()
{
int num,i,sum=0;
printf("Enter a number: ");
scanf("%d",&num);
for(i=1;i<num;i++)
{
if(num%i==0)
{
sum+=i;
}
}
if(sum==num)
{
printf("The given number %d is perfect\n",num);
}
else
{
printf("The given number %d is not perfect.",num);
}
}C Programming ExamplesExplanation
Below is an explanation of the code:
- Header Files:
#include<stdio.h>
#include<math.h>
The program includes necessary header files. stdio.h is for standard input and output functions, while math.h is for mathematical functions.
- Main Function:
main()
The program defines the main function, which is the entry point of execution.
- Variable Declaration:
int num, i, sum=0;
Declares three integer variables: num to store the user-inputted number, i for loop iteration, and sum to accumulate the divisors.
- User Input:
printf("Enter a number: ");
scanf("%d", &num);
Prompts the user to enter a number, and stores the input in the variable num.
- For Loop – Divisor Summation:
for(i=1; i<num; i++)
{
if(num%i==0)
{
sum += i;
}
}
Iterates through numbers from 1 to num-1 and checks if num is divisible by each of them. If divisible, the divisor is added to the sum.
- Perfect Number Check:
if(sum == num)
{
printf("The given number %d is perfect\n", num);
}
else
{
printf("The given number %d is not perfect.", num);
}
Checks whether the sum of divisors (sum) is equal to the original number (num). If they are equal, it prints a message indicating that the number is perfect; otherwise, it indicates that the number is not perfect.
Perfect Number:
A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself. For example, 28 is a perfect number because the sum of its divisors (1, 2, 4, 7, 14) equals 28.