C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Functions in C

Armstrong Number check using Recursive function

C Program: Armstrong Number check using Recursive function

C

#include <stdio.h>

#include <math.h>

 

// Function declarations

int countDigits(int num);

int armstrongSum(int num, int digits);

 

int main() {

    int number, digits, result;

 

    // Input number

    printf("Enter a number: ");

    scanf("%d", &number);

 

    digits = countDigits(number); // Count digits

    result = armstrongSum(number, digits); // Recursive sum

 

    // Check Armstrong condition

    if (result == number)

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

    else

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

 

    return 0;

}

 

// Function to count digits

int countDigits(int num) {

    if (num == 0)

        return 0;

    return 1 + countDigits(num / 10);

}

 

// Recursive function to calculate sum of digits raised to the power of digits

int armstrongSum(int num, int digits) {

    if (num == 0)

        return 0;

    int remainder = num % 10;

    return pow(remainder, digits) + armstrongSum(num / 10, digits);

}

Output

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


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

Explanation

  1. countDigits() Function
    • Recursively counts the number of digits in the number.
    • Example: For 153 → returns 3.
  2. armstrongSum() Function
    • Recursively computes the sum of each digit raised to the power of total digits.
    • Example:
      13+53+33=153
  3. Main Function
    • Calls both functions.
    • Compares result with the original number to decide if it’s Armstrong.