17. Write a program in c to check if a given number is a perfect number or not using a do while loop.
Perfect Number
A perfect number is equal to the sum of its integer divisors.
For eg 6 the divisors of number 6 are 1, 2, and 3 respectively. The sum of the divisors of 6 is 1 + 2 + 3 = 6 so it is a perfect number.
The sum of the divisors of 28 is 1 + 2 + 4 + 7 + 14 = 28, which is also a perfect number.
solution
1. Take a number as input and store it in a variable number.
2. Review all the numbers from 1 to the number and check whether the number is divisible by the number or not.
3. add the number to sum if the number is a divisor of the number.
4. If the sum and number is same then, print "This number is a perfect number."
5. If the number and sum is not equal then print “Number is not perfect number”.
In this approach We’ll just loop through all the numbers from 1 to the number usin do while loop and check whether the number is a divisor of the number.
Using do While Loop
In this approach, we’ll just use a do while loop to iterate through all the integers from 1 to the number and see if the number is a divisor of the number.
In this case, we simply use a do while loop to iterate over all the integers from 1 to number and check if the number is a divisor of the number.
Examples:
Input: 28
Divisors of 28 are 1, 2, 4, 7 and 14.
Sum = 1 + 2 + 4 + 7 + 14 = 28
Output: 28 is a perfect number
Input: 34
Divisors of 34 are 1, 2 and 17.
Sum = 1 + 2 + 17 = 20. 34 != 20
Output: 34 is not a perfect number
Here is source code of the C Program to check whether a given number is perfect number or not using do while loop.
C Program to check whether a given number is perfect number or not using do while loop.
/*
* program in C language using do while loop to check whether a given number is a perfect number or not
*/
#include <stdio.h>
int main(void)
{
int number,i,sum=0;
printf("\nEnter the number:\n ");
scanf("%d", &number);
i = 1;
do{
if(number % i == 0)
sum += i;
i++;
}while(i<number);
if(sum==number)
printf("\n%d is a perfect number",number);
else
printf("%d is not a perfect number",number);
}
Program Explanation
1. Accept the number as input from user and store the number in a number variable.
2. Go through all the numbers from 1 to number and see if the number is divisible by the number.
3. In the while loop, take the number, divide by i and store the result in variable sum.
4. If the sum is equals the number then print "The number is perfect number."
5. Otherwise show or print "number is not perfect".
Previous :-->> 16.Write a program in c to print the pattern of a hollow square using a while loop.
-->> NEXT:
18.Write a program in c to calculate the sum of all prime numbers between two given numbers using a for loop.
-->>ALL
Loops Assignments in c