Write a c program to check armstrong number.

Ram Pothuraju

 #include <stdio.h>

#include <math.h>


int main()

{

    int n, originalN, digits = 0, sum = 0, remainder;


    printf("Enter a positive integer: ");

    scanf("%d", &n);


    originalN = n;


    // Counting the number of digits in n

    while (originalN != 0)

    {

        originalN /= 10;

        ++digits;

    }


    originalN = n;


    // Computing the sum of the digits raised to the power of the number of digits

    while (originalN != 0)

    {

        remainder = originalN % 10;

        sum += pow(remainder, digits);

        originalN /= 10;

    }


    // Checking if the sum is equal to the original number

    if (sum == n)

    {

        printf("%d is an Armstrong number.", n);

    }

    else

    {

        printf("%d is not an Armstrong number.", n);

    }


    return 0;

}




In this program, we first take a positive integer as input from the user. We store the original number in a separate variable for later comparison. Then, we count the number of digits in the number by repeatedly dividing by 10 and incrementing a variable digits. We store the original number again in a separate variable. Then, we loop through the digits of the number and compute the sum of each digit raised to the power of the number of digits. Finally, we compare the computed sum with the original number and print the appropriate message to indicate whether the number is an Armstrong number or not.

Post a Comment

0Comments

Post a Comment (0)