Learn R Online

R Program to find Armstrong Number

In this article you will learn how to check if a number is Armstrong or not in R Programming with the help of if else structure and while loop.

What is an Armstrong Number?

How to find Armstrong Number

A number is said to be Armstrong if the sum of cubes of its digits is equal to the number itself.

See the example of 153, we want to check if it is an Armstrong number first we will find the cubes of its digits and then add them together to see the sum. If the sum is 153 i.e. equal to the number itself then it is an armstrong number else its not.

Now 153 consists of three digits 1, 5 and 3. First we will take cube of these three digits and then add the values.



1, 5, 3

Cubes of digits and sum:

= (1)3+ (5)3 + (3)3 

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

= 1 + 125 + 27

= 153

The sum of cubes of all individual digits is equal to the number itself, hence 153 is an Armstrong number. 

Armstrong Number Check Calculation:

Similarly to find if 23 is an armstrong number or not. We will take cube of 2 and 3 and then add the values.

Cubes of digits and sum:

= (2)3+ (3)3 

= 2*2*2 + 3*3*3 

= 8 + 27

= 35

35 is the sum of cubes and as it is not equal to the number itself hence 23 is not an armstrong number.

After these two examples, now it is very clear what is an armstrong number and how to check it by calculation.

Example : Find Armstrong Number

Now here is R code to check if a number is armstrong.

isArmstrong <- function(x){
  sum <- 0
  y <- x
  while(y > 0){
    digit <- y %% 10
    sum <- sum + (digit^3)
    y <- floor(y/10)

  if(x == sum){
    print(paste(x,' *** is an Armstrong Number ***'))
  } else {
    print(paste(x,'is not an Armstrong Number'))
} # Function



> isArmstrong(153)

[1] "153  *** is an Armstrong Number ***"

> isArmstrong(23)

[1] "23 is not an Armstrong Number"


First we define a function isArmstrong and initialize sum to 0. 

We get each digit of number with the help of mod or modulus operator %%Take cube of each digit and add it in sum. 

Remainder is the last digit when it is divided by 10. 

If else is used to see if sum of all cubes is equal to the number itself.

RStudio Armstrong Number Code and its Output:

Here is RStudio working code to find armstrong number.

RStudio Armstrong Function Code

if else use to find Armstrong Number
function call
R armstrong number output

Learn R is the place to learn R for all purposes from simple analytics to data science and machine learning.