Armstrong Number in C
×


Armstrong Number in C

243

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 each raised to the power of the number of digits.

For example, 153 is an Armstrong number because:

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

Here's how you can check for Armstrong numbers in C:

Algorithm to Check Armstrong Number:

Calculate the number of digits (n) in the given number.

Calculate the sum of each digit raised to the power of n.

Compare the sum with the original number.

Program to Check Armstrong Number

 //Program to Check Armstrong Number
#include<stdio.h> 
#include<math.h> 

int main() {
    int number, originalNumber, remainder, result = 0, n = 0;

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

    originalNumber = number;

    // Calculate the number of digits
    while (originalNumber != 0) {
        originalNumber /= 10;
        ++n;
    }

    originalNumber = number;

    // Calculate sum of power of each digit
    while (originalNumber != 0) {
        remainder = originalNumber % 10;
        result += pow(remainder, n);
        originalNumber /= 10;
    }

    // Check if the number is Armstrong
    if (result == number)
        printf("%d is an Armstrong number.\n", number);
    else
        printf("%d is not an Armstrong number.\n", number);

    return 0;
}
	

Output:

Enter an integer: 153
153 is an Armstrong number.

Explanation:

We first read an integer from the user.

We then calculate the number of digits in the number.

We calculate the sum of each digit raised to the power of the number of digits.

We compare the calculated sum with the original number to determine if it's an Armstrong number.


Key Points:

pow() Function: We use the pow() function from the library to calculate the power of each digit.

Variable Descriptions:

number: The number entered by the user.

original Number: A copy of the original number to calculate the number of digits.

remainder: Remainder of the number when divided by 10 (each digit).

result: The sum of each digit raised to the power of the number of digits.

n: Number of digits in the original number.

By running this program, you can check whether a given number is an Armstrong number or not in C.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments