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

int main() {
    int number, originalNumber, remainder, digits = 0, sum = 0;

    // Get user input
    printf("Enter an integer: ");
    scanf("%d", &number);

    originalNumber = number; // Store the original number for later comparison

    // Calculate the number of digits
    while (originalNumber != 0) {
        originalNumber /= 10; // Divide the number by 10
        digits++; // Increase digit count
    }

    originalNumber = number; // Reset original number for the next calculation

    // Calculate the sum of each digit raised to the power of 'digits'
    while (originalNumber != 0) {
        remainder = originalNumber % 10; // Get last digit
        sum += pow(remainder, digits); // Add the power of the digit to sum
        originalNumber /= 10; // Remove last digit
    }

    // Check if the original number is equal to the sum
    if (sum == number) {
        printf("%d is an Armstrong number.\n", number);
    } else {
        printf("%d is not an Armstrong number.\n", number);
    }

    return 0; // Indicate successful completion
}

Explanation:

Including Libraries:

Including Libraries:

c

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

We include stdio.h for input and output and math.h for mathematical functions like pow.

Main Function:

c

int main() { ... }

This is where the execution starts. It returns an integer indicating how the program finished.

Variable Declaration:

c

int number, originalNumber, remainder, digits = 0, sum = 0;

Here, number stores the user input, originalNumber is used for calculations, remainder stores each digit, digits counts the total digits, and sum accumulates the powers of the digits.

User Input:

c

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

We prompt the user for an integer and read it into number.

Calculating Number of Digits:

c

while (originalNumber != 0) {
originalNumber /= 10; // Divide the number by 10
digits++; // Count the digits
}

This loop counts the digits by dividing the number by 10 until it becomes zero.

Resetting originalNumber:

c

originalNumber = number; // Reset original number

We reset originalNumber to its original value for the next loop.

Calculating the Armstrong Sum:

c

while (originalNumber != 0) {
remainder = originalNumber % 10; // Get last digit
sum += pow(remainder, digits); // Add the power of the digit
originalNumber /= 10; // Remove last digit
}

In this loop, we extract each digit, raise it to the power of the total digit count, and add it to sum.

Checking the Armstrong Condition:

c

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

Finally, we compare the calculated sum with the original number and display the result.

OUTPUT:

Enter an integer: 153
153 is an Armstrong number.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights