Loop Exercises
Write a C program to find all Perfect numbers between 1 to n. C program to find all perfect numbers between given range. How to generate all perfect numbers between given interval using loop in C programming. Logic to find all perfect numbers in a given range in C programming.
Required knowledge
Basic C programming, If statement, For loop, Nested loop
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
Step by step descriptive logic to find Perfect numbers from 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(i=1; i<=end; i++).
- For each iteration inside loop print the value of i if it is a Perfect number.
Program to find all perfect numbers between 1 to n
/** * C program to print all Perfect numbers between 1 to n */ #include <stdio.h> int main() { int i, j, end, sum; /* Input upper limit to print perfect number */ printf("Enter upper limit: "); scanf("%d", &end); printf("All Perfect numbers between 1 to %d:\n", end); /* Iterate from 1 to end */ for(i=1; i<=end; i++) { sum = 0; /* Check whether the current number i is Perfect number or not */ for(j=1; j<i; j++) { if(i % j == 0) { sum += j; } } /* If the current number i is Perfect number */ if(sum == i) { printf("%d, ", i); } } return 0; }
Once, you got the logic to print perfect numbers from 1 to n. You can easily modify the logic to print perfect numbers in given range. I am writing the below program with little modification to print perfect numbers in given range.
Program to generate perfect numbers in given range
/** * C program to print all Perfect numbers between 1 to n */ #include <stdio.h> int main() { int i, 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(i=start; i<=end; i++) { sum = 0; /* Check whether the current number i is Perfect number or not */ for(j=1; j<i; j++) { if(i % j == 0) { sum += j; } } /* If the current number i is Perfect number */ if(sum == i) { printf("%d, ", i); } } return 0; }
Output
Enter lower limit: 1
Enter upper limit: 1000
All Perfect numbers between 1 to 1000:
6, 28, 496,