Learn how to write a C program to effectively identify and print all perfect numbers up to a specified limit, N, with our simple and easy-to-follow tutorial.
What is a Perfect Number?
A perfect number is a positive integer where all the smaller numbers that can divide into it, when added together, give the original number. For example, 6 is a perfect number because when you add up its smaller numbers that can divide into it (1, 2, and 3), the total is 6.
C Program to Print All Perfect Numbers Up to N
Here's a C program that prints all perfect numbers up to a given limit, N:
#include <stdio.h>
// Function to check if a number is perfect
int isPerfect(int num) {
int sum = 0, i;
// Loop through numbers less than 'num' to find its divisors
for(i = 1; i < num; i++) {
// Check if 'i' is a divisor of 'num'
if(num % i == 0) {
sum += i; // Add the divisor to 'sum'
}
}
return (sum == num); // Return true if 'sum' is equal to 'num'
}
// Main function
int main() {
int N, i;
// Get the limit from the user
printf("Enter the value of N: ");
scanf("%d", &N);
// Print all perfect numbers up to N
printf("Perfect numbers up to %d are: ", N);
// Loop through numbers from 1 to N
for(i = 1; i <= N; i++) {
// Check if the current number is perfect
if(isPerfect(i)) {
printf("%d ", i); // Print the perfect number
}
}
printf("\n"); // Move to the next line
return 0;
}
Program Output:
Enter the value of N: 50
Perfect numbers up to 50 are: 6 28
Code Explanation:
The above program is split into two main parts: the isPerfect
function and the main
function.
- The
isPerfect
Function: This function accepts an integer and returns whether it's a perfect number or not. Afor
loop iterates through numbers less than the given integer, checking if they're divisors. If they are, the function adds them to the sum. Finally, it checks if the sum equals the original number, returning the result. - The
main
Function: The main function prompts the user for an upper limit, N. Then it iterates from 1 to N, callingisPerfect
for each number. If a number is perfect, it prints it.
Conclusion
You've learned how to write a C program to identify and print all perfect numbers up to a specific limit, N. The program uses essential C programming constructs like loops and functions. By understanding and implementing this code, you gain a strong grasp of these key concepts, helpful in tackling more complex problems.