Armstrong Number in C

Armstrong Number in C

·

3 min read

If you're studying CS in a university then you probably have C in your course and its a very fundamental programming language which played a very important role in the development of the modern world.

As a beginner, you're supposed to solve various programming questions in your undergrad which are about math topics or some programming specific topics.

One of them is Armstrong Number

What is Armstrong Number?

Armstrong Number is basically a number whose sum of cubes is the original number

Let's consider 153.

Now if we cube its digits and add them, we get 153 again.

Such numbers are called Armstrong Numbers and now let's see how we can implement them in C.

Implementation

As usual, let us begin with the basic C programming structure.

#include <stdio.h>
int main(){
}

Now let us declare 4 Integer variables necessary for this program inside the main function.

#include <stdio.h>
int main(){
    int n,rem,arm,old;
}

Here,

VariablePurpose
nNumber
remRemainder
armArmstrong Number
oldOriginal Number

Now let us declare n=153 and arm =0.

Also assign the value of old to n.

n = 153;
arm =0;
old = n;

Now lets open a while loop with n!=0 as condition. The condition keeps running until n is not equal to 0.

while(n!=0){
}

Now use the % operator on 10 and equate it to rem like this

rem = n % 10;

Now to find the armstrong number, we have to cube the digits like this

arm = arm + rem*rem*rem;

Let us end the loop by dropping a n=n/10

n = n/10;

Now our while loop block looks something like this

while(n!=0){
        rem = n % 10;
        arm = arm + rem*rem*rem;
        n=n/10;
    }

Now we have to check if the armstrong number variable is equal to the original number old, we do this using if...else block.

We throw the checking condition in the if block and if it doesn't work out, we send the program to the else part.

if (arm==old){
     printf("Armstrong");
}
else{
     printf("Not armstrong");
}

Now run the code and you will notice the output as Armstrong , indicating that the given number is an armstrong number.

Full Code

#include <stdio.h>

int main() {
    int n,i,rem,arm,old;
     n = 153;
     arm =0;
     old = n;
    while(n!=0){
        rem = n % 10;
        arm = arm + rem*rem*rem;
        n=n/10;
    }
    if (arm==old){
        printf("Armstrong");
    }
    else{
        printf("Not armstrong");
    }
}

Conclusion

Now that's how we implement an armstrong number in C, hope you've learnt something new.

Follow my blog for more content like this.