English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structures

C Language Files

C Others

C Language Reference Manual

C program to check Armstrong number

Comprehensive Collection of C Programming Examples

In this example, you will learn to check if the integer entered by the user is an Armstrong number.

To understand this example, you should understand the followingC ProgrammingTopic:

If a positive integer satisfies the following conditions, it is called an Armstrong number (n-th order), if

abcd... = an + bn + cn + dn +

For3digit Armstrong number, the sum of the cubes of each digit equals the number itself. For example,153It is an Armstrong number because

153 = 1*1*1 + 5*5*5 + 3*3*3

Check three-digit Armstrong numbers

#include <stdio.h>
int main() {
    int num, originalNum, remainder, result = 0;
    printf("Enter an integer with three digits: ");
    scanf("%d", &num);
    originalNum = num;
    while (originalNum != 0) {
       // remainder
        remainder = originalNum % 10;
        
       result += remainder * remainder * remainder;
        
       //remove the last digit from the original number
       originalNum /= 10;
    }
    if (result == num)
        printf("%d is an Armstrong number.", num);
    else
        printf("%d is not an Armstrong number.", num);
    return 0;
}

Output Result

Enter an integer with three digits: 371
371 is an Armstrong number.

Check n-digit Armstrong numbers

#include <math.h>
#include <stdio.h>
int main() {
   int num, originalNum, remainder, n = 0;
   float result = 0.0;
   printf("Enter an integer: ");
   scanf("%d", &num);
   originalNum = num;
   //stores the number of digits in num in n
   for (originalNum = num; originalNum != 0; ++n) {
       originalNum /= 10;
   }
   for (originalNum = num; originalNum != 0; originalNum /= 10) {
       remainder = originalNum % 10;
      // stores the sum of the powers of each digit in the result
      result += pow(remainder, n);
   }
   // If num equals result, then the number is an Armstrong number
   if ((int)result == num)
    printf("%d is an Armstrong number.", num);
   else
    printf("%d is not an Armstrong number.", num);
   return 0;
}

Output Result

Enter an integer: 1634
1634 is an Armstrong number.

In this program, first calculate the number of digits of an integer and store it in n. And the pow() function is used to calculate the power of each digit in the second for loop iteration.

Comprehensive Collection of C Programming Examples