C program to find all Armstrong numbers between 1 to n

Write a C program to enter any number and print all Armstrong numbers between 1 to n. C program for Armstrong number How to print armstrong numbers between given interval using loop in C program. Generating all armstrong numbers between given range in C programming.

Example:
Input upper limit: 1000
Output: 1, 153, 370, 371, 407

Also check this program using functions - C program to find all armstrong numbers between given interval using functions.

Required knowledge

Basic C programming, For loop, Nested loop, If else

Armstrong number

Armstrong number is a special number whose sum of cube of its digits is equal to the original number. For example: 371 is an Armstrong number because
33 + 73 + 13 = 371
Before printing all armstrong numbers in a given range we must first learn how to check whether a number is armstrong number or not.

Program to find all armstrong numbers

/**
 * C program to print first n Armstrong number
 */

#include <stdio.h>

int main()
{
    int i, n, num, lastDigit, sum = 0;

    /* Reads a number from user */
    printf("Enter any number to find Armstrong number upto: ");
    scanf("%d", &n);


    printf("All Armstrong numbers between 1 to %d:\n", n);

    /*
     * Iterates from 1 to n and prints the number if it is armstrong
     */
    for(i=1; i<=n; i++)
    {
        num = i;
        sum = 0;

        /* Finds the sum of cube of digits of number */
        while(num!=0)
        {
            lastDigit = num % 10;
            sum += lastDigit * lastDigit * lastDigit;
            num = num / 10;
        }

        /*
         * Checks whether the current number is Armstrong number or not
         */
        if(i==sum)
        {
            printf("%d is ARMSTRONG NUMBER\n", i);
        }
    }

    return 0;
}


Output
Enter any number to find Armstrong number upto: 1000
All Armstrong numbers between 1 to 1000:
1 is ARMSTRONG NUMBER
153 is ARMSTRONG NUMBER
370 is ARMSTRONG NUMBER
371 is ARMSTRONG NUMBER
407 is ARMSTRONG NUMBER

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