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 :

[codesyntax lang=”c” lines=”normal”]

#include<stdio.h>
void main()
{
  int NUM,i,SUM=0;
  printf("\nENTER ANY INTERGER AND FIND IS IT PERFECT NUMBER : ");
  scanf("%d",&NUM);
  for(i=1;i<NUM;i++)
  {
    if(NUM%i==0)
    {
      SUM=SUM+i;
    }
  }
  if(SUM==NUM)
  {
    printf("\n%d IS A PERFECT NUMBER",NUM);
    printf(" SINCE SUM OF DIVISORS IS %d \n",SUM);
  }
  else
  {
    printf("\n%d IS NOT A PERFECT NUMBER",NUM);
    printf(" SINCE SUM OF DIVISORS IS %d \n",SUM);
  }
getch();
}

[/codesyntax]

SCREEN SHOTS:-

C_program_Perfect_No

C_program_Perfect_No_Output

 

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

Leave a Reply