Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to check a given number is armstrong or not

C Code Example — Loop Programs

ADVERTISEMENT

C Program to check a given number is armstrong or not

Objective

Write a C program to check if a given number is an Armstrong number.

Algorithm / Approach

  1. Read an integer n.
  2. First Pass (Count Digits): Use a loop to divide a temporary copy of n by 10 until it hits 0, counting how many digits it has.
  3. Second Pass (Calculate Sum): Use another loop on a fresh copy of n.
  4. Extract the last digit using % 10.
  5. Raise that digit to the power of the total digit count and add it to a sum: sum = sum + pow(rem, digits).
  6. If the final sum == n, it is an Armstrong number.
main.c
#include<stdio.h>
#include<math.h>
int main( ) {
 int n, sum =0, temp, rem, digits = 0;
 printf("Enter a number : ");
 scanf("%d",&n);
 temp = n;
 while(temp != 0) {
  digits++;
  temp = temp/10;
 }
 temp = n;
 while(temp != 0) {
  rem = temp%10;
  int power = pow(rem, digits);
  sum = sum + power;
  temp = temp/10;
 }
 if(n == sum) {
  printf("%d is an armstrong number");
 }
 else {
  printf("%d is not an armstrong no.");
 }
 return 0;
}

Expected Output

Enter a number : 371
371 is an armstrong number

Explanation of the Program

  • An Armstrong number (or 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, 371 is a 3-digit number. If you calculate 33 + 73 + 13 (27 + 343 + 1), it perfectly equals 371.

Complexity

Time Complexity O(log₁₀ n) - Two passes over the digits of the number.
Space Complexity O(1)
ADVERTISEMENT