C program to print all strong numbers between given interval using function

Write a function to print all strong numbers between a given interval in C programming. How to print strong numbers in a given range using functions in C programming. Write a C function to find strong numbers between 1 to n.

Example:
Input lower limit: 1
Input upper limit: 100
Output strong numbers: 1, 2, 145

Required knowledge

Basic C programming, Function

Logic to print strong numbers in range

We have already seen what are Strong numbers and how to print Strong numbers in given interval using loop also you must be knowing how to find factorial of any number. So, here what we need to do is write down entire logic of printing strong numbers in given interval into an user defined function.

Program to print strong numbers in given interval

/**
 * C program to print strong numbers in a given interval using functions
 */
 
#include <stdio.h>


/* Function declaration */
long long fact(int num);
void printStrongNumbers(int start, int end);



int main()
{
    int start, end;
    
    /* Reads starting and ending range */
    printf("Enter the lower limit to find strong number: ");
    scanf("%d", &start);
    printf("Enter the upper limit to find strong number: ");
    scanf("%d", &end);
    
    printf("All strong numbers between %d to %d are: \n", start, end);
    printStrongNumbers(start, end);
    
    return 0;
}



/**
 * Prints all strong numbers in a given range
 */
void printStrongNumbers(int start, int end)
{
    long long sum;
    int num;
    
    // Iterates from start to end
    while(start != end)
    {
        sum = 0;
        num = start;
        
        //Finds sum of factorial of digits
        while(num != 0)
        {
            sum += fact(num % 10);
            num /= 10;
        }
        
        //Checks if sum of factorial of digits equal to current number
        if(start == sum)
        {
            printf("%d, ", start);
        }
        
        start++;
    }
}




/**
 * Recursively finds factorial of any number
 */
long long fact(int num)
{
    if(num == 0)
        return 1;
    else
        return (num * fact(num-1));
}


Output
Enter the lower limit to find strong number: 1
Enter the upper limit to find strong number: 100000
All strong numbers between 1 to 100000 are:
1, 2, 145, 40585,

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment