How to check Armstrong Number by C

Profile Picture

saxenadivya859

Wednesday, 2024-08-07



To check if a number is an Armstrong number in C, you can use the following program. An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits.


Armstrong Number in C - Shiksha Online


Code:

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

// Function to calculate the number of digits in a number
int countDigits(int num) {
    int count = 0;
    while (num != 0) {
        num /= 10;
        count++;
    }
    return count;
}

// Function to check if a number is an Armstrong number
int isArmstrong(int num) {
    int originalNum, remainder, result = 0, n = 0;
    
    originalNum = num;
    n = countDigits(num);
    
    while (originalNum != 0) {
        remainder = originalNum % 10;
        result += pow(remainder, n);
        originalNum /= 10;
    }
    
    return (result == num);
}

int main() {
    int number;
    
    printf("Enter a number: ");
    scanf("%d", &number);
    
    if (isArmstrong(number))
        printf("%d is an Armstrong number.\n", number);
    else
        printf("%d is not an Armstrong number.\n", number);
    
    return 0;
}


How did you feel about this post?

😍 🙂 😐 😕 😡