C program to check perfect number; Through this tutorial, we will learn how to check perfect number in c program using for loop, while loop and function.
C Program to Check Perfect Number
- C Program to find Perfect Number using For Loop
- C Program to find Perfect Number using While Loop
- C Program to find Perfect Number using Function
C Program to find Perfect Number using For Loop
/* C Program to find Perfect Number using For Loop */ # include <stdio.h> int main() { int i, Number, Sum = 0 ; printf("\n Please Enter any number :- ") ; scanf("%d", &Number) ; for(i = 1 ; i < Number ; i++) { if(Number % i == 0) Sum = Sum + i ; } if (Sum == Number) printf("\n %d is a Perfect Number", Number) ; else printf("\n%d is not the Perfect Number", Number) ; return 0 ; }
The output of the above c program; as follows:
Please Enter any number :- 15 15 is not the Perfect Number
C Program to find Perfect Number using While Loop
/* C Program to find Perfect Number using While Loop */ # include <stdio.h> int main() { int i = 1, Number, Sum = 0 ; printf("\n Please Enter any number :- ") ; scanf("%d", &Number) ; while( i < Number ) { if(Number % i == 0) Sum = Sum + i ; i++; } if (Sum == Number) printf("\n %d is a Perfect Number", Number) ; else printf("\n%d is not the Perfect Number", Number) ; return 0 ; }
The output of the above c program; as follows:
Please Enter any number :- 6 6 is a Perfect Number
C Program to find Perfect Number using Function
/*C program to check nunber is perfect or not.*/ #include <stdio.h> /*function to check perfect number or not*/ int isPerfect(int num) { int loop, sum = 0; for (loop = 1; loop < num; loop++) { if (num % loop == 0) sum += loop; } if (sum == num) return 1; /*Perfect Number*/ else return 0; /*Not Perfect Number*/ } int main() { int num, loop; int sum; printf("Enter an integer number: "); scanf("%d", &num); if (isPerfect(num)) printf("%d is a perfect number.", num); else printf("%d is not a perfect number.", num); return 0; }
The output of the above c program; as follows:
Enter an integer number: 9 9 is not a perfect number.