10. Write a program in c to check if a given number is a perfect or not using a while loop or do while loop.
Introduction
A perfect number is a number equal to the sum of its right divisors.
For example, 28 is divisible by 1, 2,,4,7 and 14.
The sum of the divisors of 28 is 1 + 2 + 4 + 7 + 14 = 28 is also a perfect number.
Problem Description
Problem Solution
1.Take a number as input and store it in a variable.
2.Go through all the numbers from 1 to the number and check if the number is a divisor of the number.
3.If a number divides the number, add it to the sum.
4.If the sum is a number, print "This number is a perfect number".
5.If the number is not equal to sum then show message “The number is not a perfect number”.
C program source code to check whether a given number is perfect number or not using while loop.
#include<stdio.h>
int main(void)
{
int n, i, sum = 0;
printf("Enter the number: \n");
scanf("%d",&n);
i=1;
while (i< n)
{
if(n%i==0)
sum+=i;
i++;
}
if (sum==n)
printf("\n%d is a perfect number",n);
else
printf("%d is not a perfect number",n);
}
Output
Enter the number: 11
11 is not a perfect number
Enter the number: 28
28 is a perfect number
Explanation
1. Take a number as input and save it as a variable n.
2. Iterate or loop all the numbers from 1 to the number n and check whether the number is divisible by the number or not.
3. Inside the while loop, divide the number by i and save the result in a variable sum.
4. If the sum is equal to a number, print "number is a perfect number".
5. otherwise show message "The number is not a perfect number".
Previous :-->> 9.Write a program in c language to print the pattern of a pyramid using a for loop.
-->> NEXT:
11.Write a program in c programming to print the sum of all odd numbers between two given numbers using a while loop.
-->>ALL
Loops Assignments in c