C007 An interactive C program to check whether a given number is a perfect number or not

By | August 12, 2013

A positive number is called Perfect Number if it is equal to the sum of all of its positive divisors,  excluding number itself.

Let’s identify variables needed for this program.
First variable will be the one which will save the value entered by the user and it will be NUM. Second variable will be i which will be for FOR Loop. Last variable will be holding sum of  all the divisors and it will be SUM so in all three variables.
The identified variables are NUM, i,SUM.

Now, Selection of data type is int data type due to the values expected are decimals and they will be holding smaller values so int data type is sufficient.

In this program there is a requirement of generating the divisors. Here we have to Check the values from 1 to the given number. It indicates LOOP is to be taken. Best Loop for such kind of condition is FOR Loop.
Loop selected is FOR Loop.

Now give the user a message to enter a value and scan the input from the user and save it in NUM variable.
for(i=1;i<NUM;i++) this FOR loop will give you DIVIDE ERROR. So be careful while initializing i=1 instead of i=0.
For Loop will start with 1 to NUM-1.To identify whether the number is divisor or not. We have to divide that number by given number(NUM). If the remainder is zero than number entered is an divisor and if the remainder is not zero than number is not a divisor. This can be achieved by % (modulus) operator which is giving us the remainder.

The condition will be NUM%i in FOR Loop. If the remainder will be zero, INSTEAD of printing the number divisible as output values in this program, we will sum the divisors generated and save it in SUM by equation SUM=SUM+i.

If the total sum of divisor of a given number is equal to the given number itself than check this condition by SUM==NUM and if its equal than print the message NUMBER IS A PERFECT NUMBER else print message  NUMBER IS NOT A PERFECT NUMBER.

C program code :

  1. #include<stdio.h>
  2. void main()
  3. {
  4. int NUM,i,SUM=0;
  6. scanf("%d",&NUM);
  7. for(i=1;i<NUM;i++)
  8. {
  9. if(NUM%i==0)
  10. {
  11. SUM=SUM+i;
  12. }
  13. }
  14. if(SUM==NUM)
  15. {
  16. printf("\n%d IS A PERFECT NUMBER",NUM);
  17. printf(" SINCE SUM OF DIVISORS IS %d \n",SUM);
  18. }
  19. else
  20. {
  21. printf("\n%d IS NOT A PERFECT NUMBER",NUM);
  22. printf(" SINCE SUM OF DIVISORS IS %d \n",SUM);
  23. }
  24. getch();
  25. }





Note:- To understand program for sequence in detail Please SEARCH numerically example: C001, C002, etc.

Leave a Reply