C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Functions in C

Armstrong Number check using function

C Program: Armstrong Number check using function

C

#include <stdio.h>

#include <math.h>

 

// Function declaration

int isArmstrong(int num);

 

int main() {

    int number;

 

    // Input number

    printf("Enter a number: ");

    scanf("%d", &number);

 

    // Function call and result display

    if (isArmstrong(number))

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

    else

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

 

    return 0;

}

 

// Function definition

int isArmstrong(int num) {

    int original = num;

    int sum = 0, remainder, digits = 0, temp;

 

    // Count number of digits

    temp = num;

    while (temp != 0) {

        digits++;

        temp /= 10;

    }

 

    // Calculate sum of powers of digits

    temp = num;

    while (temp != 0) {

        remainder = temp % 10;

        sum += pow(remainder, digits);

        temp /= 10;

    }

 

    // Compare the sum with the original number

    if (sum == original)

        return 1;  // Armstrong

    else

        return 0;  // Not Armstrong

}

Output

 
OUTPUT 1 :
Enter a number: 153
153 is an Armstrong number.

OUTPUT 2 :
Enter a number: 123
123 is not an Armstrong number.

Explanation

  1. What is an Armstrong Number?
    A number is called an Armstrong number if the sum of its digits each raised to the power of the total number of digits equals the number itself.
    • Example:
      153 = 13+53+33 = 153
  2. Steps in the Program
    • Count number of digits in the number.
    • Compute the sum of each digit raised to that power.
    • Compare the sum with the original number.