Write a c program to check given number is perfect number or not.


Levels of difficulty: / perform operation:

check given number is perfect number or not


Program 1

#include<stdio.h>
int main(){
  int n,i=1,sum=0;

  printf("Enter a number: ");
  scanf("%d",&n);

  while(i<n){
      if(n%i==0)
           sum=sum+i;
          i++;
  }
  if(sum==n)
      printf("%d is a perfect number",i);
  else
      printf("%d is not a perfect number",i);

  return 0;
}


Result

Enter a number: 6
6 is a perfect number


Program 2

C program to print perfect numbers from 1 to 100

#include<stdio.h>
int main(){
  int n,i,sum;
 
  printf("Perfect numbers are: ");
  for(n=1;n<=100;n++){
    i=1;
    sum = 0;

    while(i<n){
      if(n%i==0)
           sum=sum+i;
          i++;
    }

    if(sum==n)
      printf("%d ",n);
  }

  return 0;
}


Result

Perfect numbers are: 6 28