C Program to check if a number is armstrong or not

Category: C Program

C Program to check if a number is armstrong or not using function

C Program to check if a number is armstrong or not using function

#include <stdio.h>
#include <math.h>

// function declaration
int isArmstrong(int);
int getNoOfDigits(int);

void main()
{
    int num;

    printf("Enter the number: ");
    scanf("%d", &num);

    if (isArmstrong(num))
        printf("%d is an armstrong number", num);
    else
        printf("%d is not an armstrong number", num);
}

// function definition
int isArmstrong(int num)
{
    // return 1 if number is armstrong else 0
    int temp = num, sum = 0, lastDigit, numOfdigits;
    numOfdigits = getNoOfDigits(num);

    while (temp > 0)
    {
        lastDigit = temp % 10;
        sum = sum + round(pow(lastDigit, numOfdigits));
        temp = temp / 10;
    }
    return sum == num; // returns 0 or 1
}

int getNoOfDigits(int num)
{
    // return number of digits in a number
    int count = 0;
    while (num > 0)
    {
        num = num / 10;
        count++;
    }
    return count++;
}

Output

Enter the number: 153
153 is an armstrong number

Recommended Posts