# C Exercises: Find perfect numbers within a given number of range

## C For Loop: Exercise-28 with Solution

Write a C program to find the 'Perfect' numbers within a given number of ranges.

**Sample Solution:**

**C Code:**

```
/*
Perfect number is a positive number which sum of all positive divisors excluding
that number is equal to that number. For example 6 is perfect number since divisor of 6 are 1, 2 and 3.
Sum of its divisor is 1 + 2 + 3 = 6
*/
#include <stdio.h> // Include the standard input/output header file.
int main(){
int n, i, sum; // Declare variables for the number being checked, loop control, and sum.
int mn, mx; // Variables for the starting and ending range of numbers.
printf("Input the starting range or number : "); // Prompt the user for the starting range.
scanf("%d", &mn); // Read the starting range from the user.
printf("Input the ending range of number : "); // Prompt the user for the ending range.
scanf("%d", &mx); // Read the ending range from the user.
printf("The Perfect numbers within the given range : "); // Print a message indicating perfect numbers are being displayed.
for(n = mn; n <= mx; n++){ // Loop through the numbers in the specified range.
i = 1; // Initialize the divisor.
sum = 0; // Initialize the sum of divisors.
while(i < n){ // While the divisor is less than the number being checked.
if(n % i == 0) // If 'i' is a divisor of 'n'.
sum = sum + i; // Add 'i' to the sum.
i++; // Increment the divisor.
}
if(sum == n) // If the sum of divisors is equal to the original number.
printf("%d ", n); // Print the perfect number.
}
printf("\n"); // Print a new line for better formatting.
return 0; // Indicate that the program has executed successfully.
}
```

Sample Output:

Input the starting range or number : 1 Input the ending range of number : 50 The Perfect numbers within the given range : 6 28

**Flowchart: **

**C Programming Code Editor:**

**Previous:** Write a c program to check whether a given number is a perfect number or not.

**Next:** Write a C program to check whether a given number is an armstrong number or not.

**What is the difficulty level of this exercise?**

Test your Programming skills with w3resource's quiz.

**Weekly Trends**- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join