R Program to check amstrong number

How to check the given number is an Armstrong number or not

Here we are explaining how to write an R program to take a number from the user and check it is an Armstrong number or not. we can use the readline() function to take input from the user (terminal). Here the prompt argument can choose to display an appropriate message for the user. We need to calculate the sum of the cube of each digit, the cubes are found out using the exponent operator

How an Amstrong number check is implemented in R Program

We are using readline() function for taking the user's input. Given below are the steps which are used in the R program to read values and checking amstrong numbers. In this R program, we accept the user's values into num by providing an appropriate message to the user using 'prompt'. Find the sum of the cube of each digit. Check the sum is equal to the given number if yes it is an Amstrong number, otherwise, it is not an Amstrong number.

ALGORITHM

STEP 1: prompting appropriate messages to the user

STEP 2: take user input using readline() into variables num

STEP 3: initialize sum=0

STEP 4:move temp= num

STEP 5:find the sum of the cube of each digit using while loop

STEP 6:If num = sum print is number is an Armstrong number

STEP 7:else print is number is not an Armstrong number

 

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"))
}
                                      

OUTPUT

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

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