C Program to Find or Generate All Armstrong Numbers From 1 to n Range and Print on Console

In this article, we are going to execute a program “C Program to Find or Generate All Armstrong Numbers From 1 to n Range and Print on Console” successfully without facing any troubles. Yes, Let’s do it using this article.

C Program to Find or Generate All Armstrong Numbers From 1 to n Range and Print on Console

C Program to Find or Generate All Armstrong Numbers From 1 to n Range and Print on Console

Source Code

/**
 * C program to print Armstrong numbers from 1 to n
 */
#include <stdio.h>
#include <math.h>

int main()
{
    int num, lastDigit, digits, sum, i, end;

    /* Input upper limit from user */
    printf("Enter upper limit: ");
    scanf("%d", &end);

    printf("Armstrong number between 1 to %d are: n", end);

    for(i=1; i<=end; i++)
    {
        sum = 0;

        /* Copy the value of num for processing */
        num = i;

        /* Find total digits in num */
        digits = (int) log10(num) + 1;

        /* Calculate sum of power of digits */
        while(num > 0)
        {
            /* Extract last digit */
            lastDigit = num % 10;

            // Find sum of power of digits
            // Use ceil() function to overcome any rounding errors by pow()
            sum = sum + ceil(pow(lastDigit, digits));

            /* Remove the last digit */
            num = num / 10;
        }

        /* Check for Armstrong number */
        if(i == sum)
        {
            printf("%d, ", i);
        }

    }

    return 0;
}

Final Words

We hope You gained a piece of knowledge about “C Program to Find or Generate All Armstrong Numbers From 1 to n Range and Print on Console“. Do visit our other programs too on our website. If you face any difficulties in this topic then ask me via the comment section. Share this article with your friends.

Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment