Write a C program to enter any number and check whether number is Strong number or not. How to check strong numbers using loop in C programming. Logic to check whether a given number is strong number or not in C program.
Example
Input
Input number: 145
Output
145 is STRONG NUMBER
Required knowledge
Basic C programming, If else, For loop
Must have programming knowledge for this program.
What is Strong number?
Strong number is a special number whose sum of factorial of digits is equal to the original number. For example: 145 is strong number. Since, 1! + 4! + 5! = 145
Logic to check Strong number
Below is the step by step descriptive logic to check strong number.
- Read a number from user which needs to be checked as strong number. Store this in some variable say num.
- Copy the original value of num to some other variable for calculations purposes. Say originalNum = num.
- Initialize another variable to store sum of factorial of digits. Say sum = 0.
- Run a loop for each extracting each digit of the given number. Inside this loop extract the last digit of num, store it in some variable say lastDigit = num % 10.
- Find factorial of lastDigit found above. Store factorial in some variable say fact.
- Add factorial to the sum i.e. sum = sum + lastDigit.
- Repeat steps 3-6 till num > 0.
- After the loop check condition for strong number. If sum == originalNum, then the given number is Strong number otherwise not.
Program to check Strong number
/** * C program to check whether a number is Strong Number or not */ #include <stdio.h> int main() { int i, originalNum, num, lastDigit, sum; long fact; /* * Read a number from user */ printf("Enter any number to check Strong number: "); scanf("%d", &num); // Copy the value of num to some other variable originalNum = num; sum = 0; /* * Calculate sum of factorial of digits */ while(num > 0) { // Extract the last digit of num lastDigit = num % 10; /* * Find factorial of last digit */ fact = 1; for(i=1; i<=lastDigit; i++) { fact = fact * i; } /* Add factorial to sum */ sum = sum + fact; num = num / 10; } /* * Strong number condition */ if(sum == originalNum) { printf("%d is STRONG NUMBER", originalNum); } else { printf("%d is NOT STRONG NUMBER", originalNum); } return 0; }
Output
Enter any number to check Strong number: 145 145 is STRONG NUMBER
Happy coding ;)
Recommended posts
- Loop programming exercises index.
- C program to find factors of any number.
- C program to find Prime factors of any number.
- C program to find HCF of any number.
- C program to find LCM of any number.
- C program to check Armstrong number.
- C program to check Perfect number.
- C program to check Prime number.