Write C Program to Check whether a given Number is Perfect Number.

 Today we learn how to Write a program to find perfect number using c language, so before we write a program we need to know about what is perfect number?

Perfect number is a number equal to sum of all natural divider of that number.

For example: 6 those divider is 1,2,3

And sum of divider: 1+2+3=6

So given number= sum of divider of that number

Now I hope show you are understand what is perfect number. before we write c program

First you need to know about …

  • Loop (in this program we use ‘for’ loop)
  • Arithmetic operator
  • Use of if-else keyword
  • And basic of c program

Source code:


#include<stdio.h>
int main(){
    int n,i,sum=0;
    printf("enter a number to check wheather number is perfect or not:");
    scanf("%d",&n);
    for(i=1;i<n;i++){
        if(n%i==0){
            sum=sum+i;
           printf("%d\n",i);
        }
      
    }
    if(sum==n){
        printf("%d is perfect number",n);
    }
    else{
        printf("%d is not perfect number",n);
    }
    return 0;
}

Output:

enter a number to check wheather number is perfect or not:28
1
2
4
7
14
28 is perfect number
enter a number to check wheather number is perfect or not:6
1
2
3
6 is perfect number
enter a number to check wheather number is perfect or not:18
1
2
3
6
9
18 is not perfect number

May this content help you



0 Comments