Write a program that finds and prints all Armstrong numbers between 1 to n

Find All Armstrong Numbers Between 1 to n in C

In this tutorial, we will write a C program to find and print all Armstrong numbers between 1 and n.

What is an Armstrong Number?

An Armstrong number (also called a narcissistic number) is a number that is equal to the sum of its digits each raised to the power of the number of digits.

Example:

153 = 1³ + 5³ + 3³
    = 1 + 125 + 27
    = 153

So, 153 is an Armstrong number.

Algorithm

  1. Input the value of n.
  2. For each number from 1 to n:
  3. Count the number of digits.
  4. Calculate the sum of each digit raised to the power of total digits.
  5. If sum equals the number, print it.

C Program


#include <stdio.h>
#include <math.h>

int main() {
    int n, i, num, digit, count;
    int sum;

    printf("Enter the value of n: ");
    scanf("%d", &n);

    printf("Armstrong numbers between 1 and %d are:\n", n);

    for(i = 1; i <= n; i++) {

        num = i;
        count = 0;
        sum = 0;

        // Count digits
        int temp = num;
        while(temp != 0) {
            count++;
            temp /= 10;
        }

        // Calculate sum of digits raised to power
        temp = num;
        while(temp != 0) {
            digit = temp % 10;
            sum += pow(digit, count);
            temp /= 10;
        }

        // Check Armstrong condition
        if(sum == num) {
            printf("%d ", num);
        }
    }

    return 0;
}

Explanation

Step 1: Input

The program takes an integer n from the user.

Step 2: Loop from 1 to n

Each number is checked individually.

Step 3: Count Digits

We count how many digits the number contains.

Step 4: Calculate Power Sum

Each digit is raised to the power of total digits using pow().

Step 5: Compare

If the calculated sum equals the original number, it is an Armstrong number.

Sample Input

Enter the value of n: 500

Output

Armstrong numbers between 1 and 500 are:
1 2 3 4 5 6 7 8 9 153 370 371 407

Time Complexity

For each number from 1 to n, we process its digits. So, the overall time complexity is approximately O(n × d), where d is the number of digits.

C program Armstrong numbers 1 to n, narcissistic number C program, Armstrong number loop example in C, C programming number problems with solution, Armstrong number between range program

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন