Perfect Number in C
Here, you will know about perfect number and get the program source code to check perfect number in c programming. We will implement this program by using 2 different ways.
- using for loop
- using function
What is perfect number in C?
A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding itself. For example, 6 is a perfect number because it is equal to the sum of its divisors (1 + 2 + 3 = 6).
Perfect Number in C program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include<stdio.h> int main() { int i,num,sum=0; printf("Enter a number:"); scanf("%d",&num); for(i=1;i<num;i++) { if(num%i==0) { sum=sum+i; } } if(sum==num) { printf("%d is a perfect number",num); } else { printf("%d is not a perfect number",num); } return 0; } |
Output 1
Enter a number : 28
28 is a perfect number
28 is a perfect number
Output 2
Enter a number:32
32 is not a perfect number
32 is not a perfect number
Perfect Number in C using Function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <stdio.h> //perfect check function int isPerfect(int num) { int sum = 0; for (int i = 1; i <= num / 2; i++) { if (num % i == 0) { sum += i; } } if (sum == num) { return 1; // It is perfect number } else { return 0; // It is not perfect number } } int main() { int n; printf("Enter a Number : "); scanf("%d", &n); if (isPerfect(n)) { printf("%d is a perfect number.\n", n); } else { printf("%d is not a perfect number.\n", n); } return 0; } |
Output
Enter a Number : 6
6 is a perfect number.
Enter a Number : 40
40 is not a perfect number.
Check out our other C programming Examples