Wednesday, January 15, 2025
HomeComputer ScienceArmstrong Number in C

Armstrong Number in C

An Armstrong number, also known as a Narcissistic number, 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³ + 5³ + 3³ = 153

In C programming, checking if a number is an Armstrong number involves three key steps:

  1. Extracting the digits: We need to get each digit of the number.
  2. Calculating the sum of the digits raised to the power of the number of digits.
  3. Comparing the sum with the original number.
See also  ETL Process in Data Warehouse

Let’s look at an example of how to implement this in C.

C Program to Check Armstrong Number:

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

int main() {
    int num, sum = 0, temp, remainder, digits = 0;
    
    // Input the number
    printf("Enter an integer: ");
    scanf("%d", &num);
    
    // Store the number in a temporary variable
    temp = num;

    // Count the number of digits in the number
    while (temp != 0) {
        temp /= 10;
        ++digits;
    }

    temp = num;
    
    // Calculate the sum of the powers of the digits
    while (temp != 0) {
        remainder = temp % 10;
        sum += pow(remainder, digits);  // Raise the digit to the power of number of digits
        temp /= 10;
    }

    // Check if the sum equals the original number
    if (sum == num)
        printf("%d is an Armstrong number.\n", num);
    else
        printf("%d is not an Armstrong number.\n", num);
    
    return 0;
}

How the Program Works:

  1. Input: The program first takes an integer input from the user.
  2. Digit Counting: It calculates the number of digits in the number.
  3. Armstrong Check: It then calculates the sum of the digits raised to the power of the number of digits and compares it to the original number.
See also  How to Create an Empty File in Linux | Touch Command

Conclusion:

The Armstrong number check is a great example of how we can manipulate digits and use mathematical functions in C. It helps reinforce the concepts of loops, conditional statements, and mathematical functions in programming.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x