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
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.
# set the number
num = as.integer(87)
# 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"))
}
## [1] "87 is not an Armstrong number"
# set the number
num = as.integer(153)
# 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"))
}
## [1] "153 is an Armstrong number"