Skip to content

C Program to Check Armstrong Number

Advertisement

An Armstrong number is an n-digit number that is equal to the sum of the nth power of its digits. For example, 153 is an Armstrong number because it has 3 digits, and 1^3 + 5^3 + 3^3 equals 153.

In this article, we’ll write a C program that can check if a given number is an Armstrong number. We’ll break down the problem into small, manageable tasks, and then solve them step by step.

C Program Structure

Here’s a high-level overview of the program we’ll write:

  1. Get the number to check from the user.
  2. Count the number of digits in the number.
  3. Calculate the sum of each digit to the power of the total number of digits.
  4. Compare the calculated sum to the original number. If they’re equal, then the number is an Armstrong number; otherwise, it’s not.

C Program Code

Now let’s look at the actual C program:

Explanation

The program starts by including two header files: stdio.h for input/output functions and math.h for the power function pow() used later in the program.

We declare five variables:

  • num: to hold the user’s input
  • originalNum: to hold a copy of num because we’ll manipulate num during the program
  • remainder: to hold the remainder of the division of originalNum by 10 (i.e., the last digit of the number)
  • n: to hold the number of digits in the number
  • result: to hold the sum of each digit to the power of n

The program then prompts the user to enter an integer. It copies this integer into originalNum and calculates the number of digits in the number.

The program then calculates the sum of each digit to the power of n using the formula result += pow(remainder, n);. After the sum is calculated, the program checks if the sum equals the original number. If the sum equals the original number, the number is an Armstrong number. If not, the number isn’t an Armstrong number.

Example

Let’s test the program with the number 371, which is an Armstrong number.

Here are the steps the program would follow:

  1. Get the input 371.
  2. Calculate the number of digits. n = 3.
  3. Calculate the sum of each digit to the power of n:

    3^3 (27) + 7^3 (343) + 1^3 (1) = 371

  4. Compare the calculated sum (371) to the original number (371). They’re equal, so the program would output “371 is an Armstrong number”.

Conclusion

In this article, we’ve looked at what an Armstrong number is and how to write a C program to check if a number is an Armstrong number. The program uses basic programming concepts, such as loops, if statements, and arithmetic operations, making it a great practice exercise for beginners in C programming.

Rahul

I, Rahul Kumar am the founder and chief editor of TecAdmin.net. I am a Red Hat Certified Engineer (RHCE) and working as an IT professional since 2009..

Leave a Reply

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


Back to top