C Programming Code Examples C > For Loops and While Loops Code Examples generate perfect numbers in given range generate perfect numbers in given range What is Perfect number? Perfect number is a positive integer which is equal to the sum of its proper positive divisors. For example: 6 is the first perfect number Proper divisors of 6 are 1, 2, 3 Sum of its proper divisors = 1 + 2 + 3 = 6. Hence 6 is a perfect number. Logic to find all Perfect number between 1 to n Input upper limit from user to find Perfect numbers. Store it in a variable say end. Run a loop from 1 to end, increment 1 in each iteration. The loop structure should look like for(x=1; x<=end; x++). For each iteration inside loop print the value of x if it is a Perfect number. /* C program to print all Perfect numbers between 1 to n */ #include <stdio.h> int main() { int x, j, start, end, sum; /* Input lower and upper limit from user */ printf("Enter lower limit: "); scanf("%d", &start); printf("Enter upper limit: "); scanf("%d", &end); printf("All Perfect numbers between %d to %d:\n", start, end); /* Iterate from start to end */ for(x=start; x<=end; x++) { sum = 0; /* Check whether the current number x is Perfect number or not */ for(j=1; j<x; j++) { if(x % j == 0) { sum += j; } } /* If the current number x is Perfect number */ if(sum == x) { printf("%d, ", x); } } return 0; }