Write a C Program to Check Armstrong Number

Prince Patel
By -
0

Write a C Program to Check Armstrong Number .

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^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
In this article, we will write a C program to check if a given number is an Armstrong number or not. We will do this without using functions or complex data structures, keeping the program simple and easy to understand.


Steps to Check for Armstrong Number

To check if a number is an Armstrong number or not, we can follow these steps:
  1. Read an integer from the user.
  2. Calculate the number of digits in the given number.
  3. Initialize a temporary variable to store the original number.
  4. Initialize a variable to store the sum of the digits raised to the power of the number of digits.
  5. Using a loop, extract each digit of the number, raise it to the power of the number of digits, and add it to the sum.
  6. Check if the sum is equal to the original number. If they are equal, the number is an Armstrong number.

Here's a  C Program to Check Armstrong Number:


    
#include<stdio.h>
#include<conio.h>
void main()
{
  	int num, originalNum, remainder, n = 0, result = 0;

        // Input from user
        printf("Enter an integer: ");
        scanf("%d", &num);

        originalNum = num;

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

        originalNum = num;

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

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

Code Explanation
  • We calculate the number of digits in the given number by repeatedly dividing it by 10 and counting the divisions until it becomes zero.
  • We store the original number in originalNum.
  • We then go through each digit of the number one by one in a loop.
  • For each digit, we raise it to the power of n (the number of digits) using the pow function and add it to the result variable.
  • After processing all the digits, we check if result is equal to the original number. If they are equal, the number is an Armstrong number, and we display an appropriate message.
Output:


Tags:

Post a Comment

0Comments

Post a Comment (0)