Tuesday, 20 December 2011

Finding Armstrong numbers in a given range

If the sum of cubes of each digit of a number is equal to the number, then the number is called as Armstrong number. Today's program is also based on Armstrong numbers.
Q. Print all Armstrong numbers in a given range entered by the user.

#include <stdio.h>

int CountDigits(int num);    //returns the number of digits in a number
int SumOfCubes(int numberofdigits, int number);   //Finds the sum of cubes of the digits in a number

int main()
    printf("Enter the range. Lower number first followed by the upper number of the range\n");
    int low, high;
    scanf("%d%d", &low, &high);
    int i, count, sum;
    printf("The numbers in this range which are Armstrong are:\n\n");
    for(i = low; i <= high; i++)
        count = CountDigits(i);
        sum = SumOfCubes(count, i);
        if(sum == i)
          printf("%d\n", i);

    return 0;

int SumOfCubes(int numberofdigits, int number)
    int digarray[15];     //This array will contain the digits in the number
    int i;
    for(i = 0; i < numberofdigits; i++)
        digarray[i] = number % 10;      //Fill the digarray with individual digits
        number /= 10;

    int sum = 0, j;
    for(j = 0; j < numberofdigits; j++)
        sum = sum + (digarray[j] * digarray[j] * digarray[j]);  //Find sum of cubes of digits

    return sum;

int CountDigits(int num)
    int i = 0;
        num /= 10;

    return i;

Sample output:

Most of the program is self explanatory. Rest of the things have been cleared by comments. Please leave comments if you want to make any correction or suggest a new concept.

No comments:

Post a Comment