Q:

Write C program to print perfect numbers between given interval using function

0

Write C program to print perfect numbers between given interval using function

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

I have used Code::blocks 12 compiler for debugging purpose. But you can use any C programming language compiler as per your availability.

#include <stdio.h>
 
// Function declarations
int isPerfect(int num);
void printPerfect(int start, int end);
 
 
 
int main()
{
    int start, end;
 
    // Inputting 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;
}
 
int isPerfect(int num)
{
    int i, sum;
 
    // Finding 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;
}
 
//Printing all perfect numbers
void printPerfect(int start, int end)
{
    // Iterating from start to end
    while(start <= end)
    {
        if(isPerfect(start))
        {
            printf("%d ", start);
        }
 
        start++;
    }
}

Result:

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write C program to find power of a number using re... >>
<< Write C program to find diameter, circumference an...