Write a function to print all perfect numbers in a given interval in C programming. How to print all perfect numbers in a given range using functions in C program. C program to print all perfect numbers between 1 to n using functions.
Example
Input
Input lower limit: 1 Input upper limit: 100
Output
Perfect numbers: 6, 28
Required knowledge
Basic C programming, If else, For loop, While loop, Functions
Must know – Program to print all perfect numbers in a given range using loop.
Declare function to print all perfect numbers in given range
- First give meaningful name to the function. Say
printPerfect()
will print all perfect numbers in given range. Along with this declare and define one more functionint isPerfect(int num);
to check perfect number. - Next the function must accept two parameters i.e. start and end limit to print perfect numbers in range. Hence, the function declaration should look like
printPerfect(int start, int end);
- Finally the function prints all perfect numbers in given range returning nothing. Hence, return type of the function must be
void
.
Final function declaration to print all perfect numbers in given range is – void printPerfect(int start, int end);
Program to print perfect numbers in given range using functions
/**
* C program to print all perfect numbers in given range using function
*/
#include <stdio.h>
/* Function declarations */
int isPerfect(int num);
void printPerfect(int start, int end);
int main()
{
int start, end;
/* Input lower and upper limit to print perfect numbers */
printf("Enter lower limit to print perfect numbers: ");
scanf("%d", &start);
printf("Enter upper limit to print perfect numbers: ");
scanf("%d", &end);
printf("All perfect numbers between %d to %d are: \n", start, end);
printPerfect(start, end);
return 0;
}
/**
* Check whether the given number is perfect or not.
* Returns 1 if the number is perfect otherwise 0.
*/
int isPerfect(int num)
{
int i, sum;
/* Finds sum of all proper divisors */
sum = 0;
for(i=1; i<num; i++)
{
if(num % i == 0)
{
sum += i;
}
}
/*
* If sum of proper positive divisors equals to given number
* then the number is perfect number
*/
if(sum == num)
return 1;
else
return 0;
}
/**
* Print all perfect numbers between given range start and end.
*/
void printPerfect(int start, int end)
{
/* Iterates from start to end */
while(start <= end)
{
if(isPerfect(start))
{
printf("%d, ", start);
}
start++;
}
}
Output
Enter lower limit to print perfect numbers: 1 Enter upper limit to print perfect numbers: 10000 All perfect numbers between 1 to 10000 are: 6, 28, 496, 8128,
Happy coding 😉
Recommended posts
- Function and recursion programming exercise index.
- C program to find prime numbers in given range using function.
- C program to find strong numbers in given range using function.
- C program to find armstrong numbers in given range using function.
- C program to check even number using function.
- C program to print all natural numbers in given range using recursion.