FYBCom(CA) C Practical Slip 2 Q 1.B

C Program to Check Whether a Number is a Perfect Number (Using For Loop)

1.Introduction

In this blog,we will learn how to write a simple C program to check whether a number entered by the user is a perfect number.A perfect number is a number whose sum of proper divisors equals the number itself.

2.Problem Statement

Question:
Write a C program to accept a number from the user and check whether it is a perfect number using a for loop.

3.Logic

A perfect number is a number that is equal to the sum of its proper divisors (excluding itself).
Steps:
1.Declare variables for the number,sum,and loop counter.
2.Ask the user to input a number.
3.Use a for loop from 1 to number-1 to find all divisors.
4.Add divisors to sum.
5.Check if sum equals the number.
6.Display the result.

Example:
6 → divisors are 1,2,3 → sum=6 → perfect number
28 → divisors are 1,2,4,7,14 → sum=28 → perfect number

4.Source Code

#include<stdio.h>

int main()
{
    int num,i,sum=0;

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

    for(i=1;i<num;i++)
    {
        if(num%i==0)
        {
            sum+=i;
        }
    }

    if(sum==num)
        printf("%d is a perfect number.",num);
    else
        printf("%d is not a perfect number.",num);

    return 0;
}

5.Sample Output

Enter a number:6
6 is a perfect number.

Enter a number:10
10 is not a perfect number.

6.Viva Questions

1.What is a perfect number?
Answer: A perfect number is a number equal to the sum of its proper divisors.

2.Why do we use a for loop in this program?
Answer: To iterate from 1 to number-1 and check all divisors.

3.What is the purpose of the if(num%i==0) condition?
Answer: To check if i is a divisor of the number.

4.Can a number be negative and perfect?
Answer: No, only positive integers can be perfect numbers.

5.What is the value of sum for number 28?
Answer: 28, because 1+2+4+7+14=28.

Conclusion

This simple C program teaches beginners how to use loops, conditional statements, and arithmetic operations to solve real-world math problems.Practice with different numbers to strengthen your understanding of loops and conditions.

Spread the love

Leave a Comment

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

Scroll to Top