Coding Practice

Write a C program to print all Armstrong numbers between 1 to n

Print all Armstrong numbers between 1 to n
Sample Output
Enter a limit for armstrong numbers: 900

All armstrong numbers 1 to 900: 1 2 3 4 5 6 7 8 9 153 370 371 407
Source Code
#include<stdio.h>
#include<math.h>

//Print all Armstrong numbers between 1 to n

int main()
{
    int i, limit, number, numberClone, digit, count = 0, newNumber = 0;

    printf("Enter a limit for armstrong numbers: ");
    scanf("%d", &limit);

    printf("\nAll armstrong numbers 1 to %d: ", limit);
    for(i = 1; i <= limit; i++)
    {
        number = i;
        numberClone = number;
        while(number != 0)
        {
            digit = (number%10);
            number /= 10;
            count++;
        }

        number = numberClone;
        while(number != 0)
        {
            digit = (number%10);
            number /= 10;

            newNumber += pow(digit, count);
        }

        if(numberClone == newNumber)
        {
            printf("%d ", newNumber);
        }

        count = 0;
        newNumber = 0;
    }
    printf("\n\n");

    return 0;
}
Sample Output
Enter a limit for armstrong numbers: 900

All armstrong numbers 1 to 900: 0 1 2 3 4 5 6 7 8 9 153 370 371 407

No comments:

Post a Comment

Change Theme
X