Finding Armstrong Number in C

CCBeginner
Practice Now

Introduction

In this lab, we will learn about Armstrong number and write a program in C to verify whether a number is an Armstrong number or not. An Armstrong number is a number, that is the sum of its own digits each raised to the power of the number of digits.

For example,

153 is an Armstrong number, because 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27.
371 is an Armstrong number, because 371 = 3^3 + 7^3 + 1^3 = 27 + 343 + 1.

Create a new C file

First, we need to create a new C file in the ~/project/ directory, let's name it main.c.

touch ~/project/main.c

Finding Armstrong numbers between 1 to 500

Let's write a C program to find Armstrong numbers between 1 to 500.

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

int main() {
    printf("\nArmstrong numbers between 1 to 500 are: \n");

    for (int i = 1; i <= 500; i++) {
        int t = i, sum = 0;
        while (t != 0) {
            int digit = t % 10;
            sum += pow(digit, 3);
            t /= 10;
        }
        if (sum == i) {
            printf("%d ", i);
        }
    }

    return 0;
}

Checking if a number is an Armstrong number

Now let's write a C program to check whether a number is an Armstrong number or not.

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

int main() {
    int n, sum = 0;
    printf("Enter a number: ");
    scanf("%d", &n);

    int temp = n;
    while (temp != 0) {
        int digit = temp % 10;
        sum += pow(digit, 3);
        temp /= 10;
    }

    if (sum == n) {
        printf("%d is an Armstrong number.\n", n);
    } else {
        printf("%d is not an Armstrong number.\n", n);
    }

    return 0;
}

Putting it all together

Let's put both programs together in our main.c file.

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

int main() {
    // Armstrong numbers between 1 to 500
    printf("Armstrong numbers between 1 to 500 are: \n");

    for (int i = 1; i <= 500; i++) {
        int t = i, sum = 0;
        while (t != 0) {
            int digit = t % 10;
            sum += pow(digit, 3);
            t /= 10;
        }
        if (sum == i) {
            printf("%d ", i);
        }
    }

    printf("\n");

    // Checking if a number is Armstrong number
    int n, sum = 0;
    printf("Enter a number: ");
    scanf("%d", &n);

    int temp = n;
    while (temp != 0) {
        int digit = temp % 10;
        sum += pow(digit, 3);
        temp /= 10;
    }

    if (sum == n) {
        printf("%d is an Armstrong number.\n", n);
    } else {
        printf("%d is not an Armstrong number.\n", n);
    }

    return 0;
}

Summary

In this lab, we learned about Armstrong numbers and how to find them in a given range, and how to check whether a number is an Armstrong number or not. We hope you enjoyed this lab and it helped you learn more about C programming.

Other C Tutorials you may like