C Program to Find Perfect Number using while loop


Lets write a C program to check if user entered number is a perfect number or not, using while loop.

Related Read:
Basic Arithmetic Operations In C
while loop in C programming

Perfect Number: A number is called perfect number if sum of its divisors(except the number itself) is equal to the number.

For Example: If the user entered number is 6. The numbers which perfectly divide 6 are 1, 2, 3 and 6. Leave 6 and add all other numbers. i.e., 1 + 2 + 3 = 6. So the entered number and the sum are equal. So 6 is a perfect number.

Source Code: C Program to Find Perfect Number using while loop

#include<stdio.h>

int main()
{
    int num, count = 1, sum = 0;

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

    while(count < num)
    {
        if(num%count == 0)
        {
            sum = sum + count;
        }
        count++;
    }

    if(sum == num)
    {
        printf("\n%d is a perfect number\n", num);
    }
    else
    {
        printf("\n%d is not a perfect number\n", num);
    }

    return 0;
}

Output 1
Enter a number
5
5 is not a perfect number

Output 2
Enter a number
6
6 is a perfect number

Output 3
Enter a number
25
25 is not a perfect number

Output 4
Enter a number
28
28 is a perfect number

Video Tutorial: C Program to Find Perfect Number using while loop


[youtube https://www.youtube.com/watch?v=0JBSVq4dTeA]

YouTube Link: https://www.youtube.com/watch?v=0JBSVq4dTeA [Watch the Video In Full Screen.]

Logic To Find Perfect Number using while loop

We initialize variables count to 1 and sum to 0. Next we ask the user to enter a number. We iterate through while loop until value of count is less than the user entered number. Inside while loop we increment the value of variable count by one for each iteration. Inside while loop we also check for the condition – if user entered number modulo division value of count is equal to 0. If its true we add the value of count to the previous value of sum.

After control exits while loop we check if the value of sum and number entered by the user are same. If its same, then the user entered number is perfect number. If not, the number is not a perfect number.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

Your email address will not be published. Required fields are marked *