Cover Image for Armstrong Number in C
95 views

Armstrong Number in C

An Armstrong number (also known as a narcissistic number or pluperfect digital invariant) is a number that is equal to the sum of its own digits raised to the power of the number of digits. For example, 153 is an Armstrong number because:

1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

Here’s a C program to check if a given number is an Armstrong number:

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

int main() {
    int num, originalNum, remainder, n = 0;
    double 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;

    // Calculate the Armstrong number
    while (originalNum != 0) {
        remainder = originalNum % 10;
        result += pow(remainder, n);
        originalNum /= 10;
    }

    if ((int)result == num) {
        printf("%d is an Armstrong number.\n", num);
    } else {
        printf("%d is not an Armstrong number.\n", num);
    }

    return 0;
}

In this program:

  1. We take an integer input from the user.
  2. We make a copy of the original number (originalNum) to later compare with the calculated result.
  3. We count the number of digits in the original number by repeatedly dividing it by 10 and incrementing n.
  4. We then calculate the Armstrong number by repeatedly taking the remainder of the original number when divided by 10, raising it to the power of n, and adding it to result.
  5. Finally, we compare the calculated result (converted to an integer) with the original number to determine whether it’s an Armstrong number or not and print the result accordingly.

Compile and run the program, and it will check if the entered number is an Armstrong number or not.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS