Open In App

C Program to Print Armstrong Numbers Between 1 to 1000

Last Updated : 23 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Armstrong numbers are those numbers in which the sum of digits raised to the power of a number of digits in that number will be equal to the number itself. Here will see how to build a C Program to Display Armstrong numbers between 1 to 1000.

Example:

       153
   13 + 53 + 33
1 + 125 + 27 = 153

Approach 1:

  1. Count the number of digits in the number.
  2. Then calculate the sum of digits raised to the power of the number of digits in that number.
  3. Check whether it is equal to the number, if yes then print it.

C




// C Program to Display Armstrong
// numbers between 1 to 1000
#include <math.h>
#include <stdio.h>
 
int main()
{
    int i, sum, num, count = 0;
    printf(
        "All Armstrong number between 1 and 1000 are:\n");
 
    // This loop will run for 1 to 1000
    for (i = 1; i <= 1000; i++) {
        num = i;
        // Count number of digits.
        while (num != 0) {
            num /= 10;
            count++;
        }
        num = i;
        sum = pow(num % 10, count)
              + pow((num % 100 - num % 10) / 10, count)
              + pow((num % 1000 - num % 100) / 100, count);
        // Check for Armstrong Number
        if (sum == i) {
            printf("%d ", i);
        }
        count = 0;
    }
}


Output

All Armstrong number between 1 and 1000 are:
1 2 3 4 5 6 7 8 9 153 370 371 407 

Time Complexity: O(n * k) where n is the range of numbers to be checked (1 to 1000 in this case) and k is the maximum number of digits in any number in the range (3 in this case). This is because the loop runs for each number in the range and for each number, we calculate the sum of its digits raised to the power of k.

Space Complexity: O(1) as we are only using a constant amount of extra space for variables to store the count, sum, and current number being checked.

Approach 2:

All one-digit numbers are Armstrong numbers.

C




// C Program to Display Armstrong
// numbers between 1 to 1000
#include <stdio.h>
#include <math.h>
 
int main()
{
    int i, digit1, digit2, digit3, sum, num;
    printf("All Armstrong number between 1 and 1000 are:\n");
 
    // This loop will run for 1 to 1000
    for (i = 1; i <= 1000; i++)
    {
        num = i;
        // All single digit numbers are Armstrong number.
        if (num <= 9)
        {
            printf("%d ", num);
        }
        else
        {
            sum = pow(num % 10, 3) + pow((num % 100 - num % 10) / 10, 3) + pow((num % 1000 - num % 100) / 100, 3);
            if (sum == i)
            {
                printf("%d ", i);
            }
        }
    }
}


Output

All Armstrong number between 1 and 1000 are:
1 2 3 4 5 6 7 8 9 153 370 371 407 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads