C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Functions in C

Function for perfect number

C Program: Function for perfect number

C

#include <stdio.h>

 

// Function declaration

int isPerfect(int num);

 

int main() {

    int number;

 

    // Input number

    printf("Enter a number: ");

    scanf("%d", &number);

 

    // Function call

    if (isPerfect(number))

        printf("%d is a Perfect number.\n", number);

    else

        printf("%d is not a Perfect number.\n", number);

 

    return 0;

}

 

// Function to check perfect number

int isPerfect(int num) {

    int sum = 0;

 

    // Find divisors and sum them

    for (int i = 1; i <= num / 2; i++) {

        if (num % i == 0)

            sum += i;

    }

 

    // Check if sum equals original number

    if (sum == num)

        return 1;  // Perfect number

    else

        return 0;  // Not perfect

}

Output

 
OUTPUT 1 :
Enter a number: 6
6 is a Perfect number.

OUTPUT 2 :
Enter a number: 10
10 is not a Perfect number.

Explanation

  1. What is a Perfect Number?
    A number is called a Perfect Number if the sum of its proper divisors (excluding itself) equals the number.
    • Example: 6
      Divisors: 1, 2, 3
      Sum = 1 + 2 + 3 = 6
    • So, 6 is a Perfect Number.
  2. Function isPerfect(int num)
    • Loops from 1 to num/2 (since no divisor is greater than half the number).
    • Adds up all divisors.
    • Returns 1 if the sum equals the number, else returns 0.