R Program to check 3 digit armstrong number

February 4, 2023, Learn eTutorial

What is an Armstrong number?

An Armstrong number is a number, where the sum of the powers (digit raised to the count of digits) of each digit of the number equals that number. An integer of n digits can be called an Armstrong number if it satisfies the following condition,



  • a,b,c,d... are the digits
  • n is the count of digits

How to write an R program to check the given 3-digit number is Armstrong?

A three-digit number can call an Armstrong number if the sum of the cubes of each digit of the number equals that number. For example, take 153, the digits of 153 are 1,5 & 3. The cubes of each digit are as shown below.

  • 13 = 1 x 1 x 1 = 1
  • 53 = 5 x 5 x 5 = 125
  • 33 = 3 x 3 x 3 = 27

Then the sum of the cubes: 1 + 125 + 27 = 153 so it is an Armstrong number.

In this R program, we accept the user's input, a 3-digit number into num by providing an appropriate message to the user using 'prompt' inside the readLine() function. Using a while loop extract each digit and find the sum of the cubes of each digit. After calculation check the sum is equal to the given number itself; if yes then it is an Amstrong number, otherwise, it is not.


STEP 1: Prompting appropriate messages to the user take user input using readline() into variable num

STEP 2: Initialize sum=0 and move temp = num

STEP 3: Find the sum of the cube of each digit using while loop with condition temp > 0

  • Split a digit of the number with a mod by 10 operation
  • Calculate the sum of the cube of that digit with previous
  • Remove that digit and take the rest of the digits by a division with 10 operation

STEP 4: Compare the sum with num, if they are equal then print the number is an Armstrong number otherwise not.

To understand more about the concept, we assure you our blog The basics of Armstrong numbers will help you very much.

We recommend you to go through this related R program also, a number with n digits is Armstrong or not 

R Source Code

                                          num = as.integer(readline(prompt="Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while(temp > 0) {
    digit = temp %% 10
    sum = sum + (digit ^ 3)
    temp = floor(temp / 10)
if(num == sum) {
    print(paste(num, "is an Armstrong number"))
} else {
    print(paste(num, "is not an Armstrong number"))


Enter a number: 230
[1] "230 is not an Armstrong number"

Enter a number: 370
[1] "370 is an Armstrong number"