Examples of C part 26 check number is perfect number or not

Program :
#include<stdio.h>
#include<math.h>
main()
{
  int num,i,sum=0;
  printf("Enter a number to know whether it is perfect or not\n");
  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 because the sum of its divisors are %d\n",num,sum);
  }
}
Output:
Enter a number to know whether it is perfect or not
8
The given number 8 is not perfect because the sum of its divisors are 7
Explanation:
  1. The program starts with initializing :
    • num → To store input from user
    • i → used as helping variable
    • sum → To store output
  2. printf("Enter a number to know whether it is perfect or not\n");
    scanf("%d",&num);
    Takes input from user and is stored in num. Lets take num=6
  3. for(i=1;i<num;i++)
    {
    if(num%i==0)
    {
    sum+=i;
    }
    }
    This is the main logic of this program.Lets take num=6
    • Iteration 1i=1,1<6; which is true so the loop executes
      • num%i → 6%1=0→0==0 which is true so if part is executed
        • sum+=i → sum=0+1→sum=1
        • Now i increments by 1 so i=2
    • Iteration 2i=2,2<6; which is true so the loop executes
      • num%i → 6%2=0→0==0 which is true so if part is executed
        • sum+=i → sum=1+2→sum=3
        • Now i increments by 1 so i=3
    • Iteration 3i=3,3<6; which is true so the loop executes
      • num%i → 6%3=0→0==0 which is true so if part is executed
        • sum+=i → sum=3+3→sum=6
        • Now i increments by 1 so i=4
    • Iteration 4i=4,4<6; which is true so the loop executes
      • num%i → 6%4=2→2==0 which is flase so if part is not executed
        • sum+=i → sum=6(remains same)
        • Now i increments by 1 so i=5
    • Iteration 5i=5,5<6; which is true so the loop executes
      • num%i → 6%5=1→1==0 which is flase so if part is not executed
        • sum+=i → sum=6(remains same)
        • Now i increments by 1 so i=6
    • Iteration 6i=6,6<6; which is flase so the loop terminates
  4. The final output which is stored in sum=6
  5. if(sum==num)
    {
    printf("The given number %d is perfect\n",num);
    
    }
    else
    {
    printf("The given number %d is not perfect because the sum of its divisors are %d\n",num,sum);
    }
    Now sum is compared with the original number given as input ans if they are equal then it is a perfect number else not
  6. As sum=6 and num=6 so 6 is a perfect number.
  7. The divisors of 6 are 1,2,3 and the sum is 1+2+3=6 so sum and number is same which is why it is perfect number
  8. If we take 8 as number its divisors are 8=1,2,4 and its sum is 1+2+4=7 which is not equal to the input we gave.