what is armstrong number in c

11 months ago 22
Nature

An Armstrong number is a number that is equal to the sum of the nth power of each digit. In other words, if we take each digit of a number, raise it to the power of the number of digits, and add them up, the result should be the original number. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153. To check if a number is an Armstrong number in C, we can use the following algorithm:

  1. Read the number from the user.
  2. Store the number in a separate variable.
  3. Count the number of digits in the number.
  4. For each digit in the number, raise it to the power of the number of digits and add it to a running total.
  5. Compare the running total to the original number.
  6. If they are equal, the number is an Armstrong number. Otherwise, it is not.

Here is an example C program to check if a number is an Armstrong number:

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

int main() {
    int num, originalNum, remainder, n = 0;
    float result = 0.0;

    printf("Enter an integer: ");
    scanf("%d", &num);

    originalNum = num;

    // Count the number of digits
    while (originalNum != 0) {
        originalNum /= 10;
        ++n;
    }

    originalNum = num;

    // Raise each digit to the power of the number of digits and add to running total
    while (originalNum != 0) {
        remainder = originalNum % 10;
        result += pow(remainder, n);
        originalNum /= 10;
    }

    // Compare running total to original number
    if ((int)result == num)
        printf("%d is an Armstrong number.", num);
    else
        printf("%d is not an Armstrong number.", num);

    return 0;
}

Note that we need to include the math.h library to use the pow() function, which raises a number to a given power.