Here we are going to write a perfect number program in c using function. Earlier we did this perfect number program normally. You may like to see : Perfect Number in C. This time we will do it using function.
There are mainly two ways of doing perfect number c program i.e., perfect number program in c using for loop and perfect number program in c while loop.
We will implement both ways using function. But before that do you know what perfect numbers are?
What is a Perfect Number?
A perfect number is a positive number which is equal to the sum of its divisors excluding the number itself.
Example -
• 6 = 1 + 2 + 3 = 6
• 28 = 1 + 2 + 4 + 7 + 14 = 28
Lets discuss about the approach now.
First we will create a function named perfectchk() of void return type that is it won't return anything and it will take one integer as parameter. The integer which we are sending as parameter is the number which we want to check for Perfect. Then within that function we will print whether the given number is Perfect or not. Then in main() function we will call the perfectchk() function, that's it. Now lets code it.
Perfect Number Program in C using for loop using function
#include <stdio.h>
void perfectchk(int n){
int sum=0;
for(int i=1; i<n; i++)
{
if(n%i==0)
{
sum+=i;
}
}
if(sum==n)
{
printf("%d is a perfect number",n);
}
else
{
printf("%d is not a perfect number");
}
}
int main(){
int n;
printf("Enter a Number : ");
scanf("%d",&n);
perfectchk(n);
return 0;
}Output
Enter a Number : 6
6 is a perfect number
Enter a Number : 25
25 is not a perfect numberPerfect Number Program in C using while loop using function
#include <stdio.h>
void perfectchk(int n){
int sum=0;
while(i<n)
{
if(n%i==0)
{
sum+=i;
i++;
}
}
if(sum==n)
{
printf("%d is a perfect number",n);
}
else
{
printf("%d is not a perfect number");
}
}
int main(){
int n;
printf("Enter a Number : ");
scanf("%d",&n);
perfectchk(n);
return 0;
}
Output
Enter a Number : 6
6 is a perfect number
Enter a Number : 25
25 is not a perfect numberMore like this
• Program to print inverted pyramid pattern of numbers using function
• Factorial of a number program in c using function
• Prime Number check in C using function
• Palindrome Number in C using function
• Add two numbers in C using function

Post a Comment
If you have any doubts, please let me know