- Write a C program to print all perfect numbers between 1 to N using for loop.
Required Knowledge
- C printf and scanf functions
- For loop in C
A perfect number is a positive number, that is equal to sum of its positive divisor.
For Example : 6 is a perfect number as positive factors of 6 are 1, 2 and 3 whose sum is 6.
C program to print all perfect numbers between 1 to N using for loop
#include<stdio.h> #include<conio.h> int main () { int num, i, divSum, counter; printf("Enter a number\n"); scanf("%d", &num); /* Check for every number between 1 to num, whether it is perfect number or not */ for(counter = 1; counter <= num; counter++){ /* Find all divisors of a number between 1 to num/2 and add it to divSum */ divSum = 0; for (i = 1; i <= counter/2; i++) { if (counter % i == 0) { divSum += i; } } /* Check if Divisor sum is equal to input number */ if (divSum == counter) printf("%d is a Perfect Number\n", counter); } getch(); return 0; }
Output
Enter a number 500 6 is a Perfect Number 28 is a Perfect Number 496 is a Perfect Number