C program to check whether a number is an Armstrong number or not

Estimated read time 4 min read

C program to check whether a number is an Armstrong number or not checks if a given number is an Armstrong number or not. An Armstrong number is a number that is equal to the sum of the nth power of each digit in the number.

For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153. The c program first prompts the user to enter a number,

then counts the number of digits in the number and calculates the sum of the nth power of each digit. If the calculated sum is equal to the entered number, the program outputs that the number is an Armstrong number, otherwise, it outputs that the number is not an Armstrong number.

  • The program first declares several integer variables – num, originalNum, remainder, result, and n.
  • It prompts the user to enter an integer using the printf and scanf functions.
  • The program then counts the number of digits in the entered integer by dividing it by 10 repeatedly in a while loop and incrementing the value of n.
  • The program then calculates the sum of the nth power of each digit of the entered integer in a while loop using the pow() function from the math.h library.
  • If the calculated sum is equal to the entered integer, the program outputs that the number is an Armstrong number. Otherwise, it outputs that the number is not an Armstrong number.
#include <stdio.h>
#include <math.h>

int main() {
    int num, originalNum, remainder, result = 0, n = 0;

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

    originalNum = num;

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

    originalNum = num;

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

    if (result == num)
        printf("%d is an Armstrong number.", num);
    else
        printf("%d is not an Armstrong number.", num);

    return 0;
}
C program to check whether a number is an Armstrong number or not
C program to check whether a number is an Armstrong number or not
output
output
admin https://study-from-here.com

Digital Marketing Consultants and Social Media Marketing Expert with over 3 years of rich experience in various Branding, Promotions, business directories, On pages and off page optimization, Link building Advertising, Research, paid advertisement, content writing and marketing

You May Also Like

More From Author

1 Comment

Add yours

+ Leave a Comment