C Program to Check Armstrong Number

1. Introduction

An Armstrong number is a number that is equal to the sum of its own digits raised to the power of the number of digits. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153

2. Program Overview

1. Prompt the user to input a number.

2. Check if the given number is an Armstrong number.

3. Display the result to the user.

3. Code Program

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

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

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

    originalNum = num;

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

    originalNum = num;

    // Check if the number is Armstrong
    while (originalNum != 0) {
        remainder = originalNum % 10;
        result += pow(remainder, n);
        originalNum /= 10;
    }

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

    return 0;
}

Output:

For input 153:
153 is an Armstrong number.

For input 120:
120 is not an Armstrong number.

4. Step By Step Explanation

1. We first calculate the number of digits (n) in the given number.

2. For each digit in the number, we raise it to the power of n and add it to the result variable.

3. Finally, we check if the sum (result) is equal to the original number. If it is, then the number is an Armstrong number, otherwise, it's not.

Comments