Menu
×
Tutorials Ms Word Tutorial Ms Excel Tutorial Ms PowerPoint Tutorial C Language Tutorial C++ Tutorial C Sharp Tutorial Visual Basic Tutorial HTML Tutorial CSS Tutorial JavaScript Tutorial WordPress Tutorial
     ❯   

ADVERTISEMENT

Check Perfect Number or Not

#include<stdio.h>
#include<math.h>
main()
{
  int num,i,sum=0;
  printf("Enter a number: ");
  scanf("%d",&num);
  for(i=1;i<num;i++)
  {
    if(num%i==0)
    {
      sum+=i;
    }
  }
  if(sum==num)
  {
    printf("The given number %d is perfect\n",num);
  }
  else
  {
    printf("The given number %d is not perfect.",num);
  }
}
C Programming Examples
OUTPUT
Enter a number: 67
The given number 67 is not perfect.
C Programming Examples

Below is an explanation of the code:

  1. Header Files:
   #include<stdio.h>
   #include<math.h>

The program includes necessary header files. stdio.h is for standard input and output functions, while math.h is for mathematical functions.

  1. Main Function:
   main()

The program defines the main function, which is the entry point of execution.

  1. Variable Declaration:
   int num, i, sum=0;

Declares three integer variables: num to store the user-inputted number, i for loop iteration, and sum to accumulate the divisors.

  1. User Input:
   printf("Enter a number: ");
   scanf("%d", &num);

Prompts the user to enter a number, and stores the input in the variable num.

  1. For Loop – Divisor Summation:
   for(i=1; i<num; i++)
   {
     if(num%i==0)
     {
       sum += i;
     }
   }

Iterates through numbers from 1 to num-1 and checks if num is divisible by each of them. If divisible, the divisor is added to the sum.

  1. Perfect Number Check:
   if(sum == num)
   {
     printf("The given number %d is perfect\n", num);
   }
   else
   {
     printf("The given number %d is not perfect.", num);
   }

Checks whether the sum of divisors (sum) is equal to the original number (num). If they are equal, it prints a message indicating that the number is perfect; otherwise, it indicates that the number is not perfect.

Perfect Number:
A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself. For example, 28 is a perfect number because the sum of its divisors (1, 2, 4, 7, 14) equals 28.

Spread the love
Scroll to Top
Scroll to Top