Course
Data Frames
Convert a List to a DataframeCreate an Empty DataframeCombine Two Dataframe into OneChange Column Name of a DataframeExtract Columns From a DataframeDrop Columns in a DataframeReorder Columns in a DataframeSplit DataframeMerge Multiple DataframesDelete Rows From DataframeMake a List of DataframesIntroduction
"Hello World" ProgramAdd Two VectorsFind Sum, Mean and Product of Vector in R ProgrammingTake Input From UserGenerate Random Number from Standard DistributionsSample from a PopulationFind Minimum and MaximumSort a VectorStrings
Concatenate Two StringsFind the Length of a StringCheck if Characters are Present in a StringExtract n Characters From a StringReplace Characters in a StringCompare two StringsConvert Factors to CharactersTrim Leading and Trailing WhitespacesVectors
Concatenate a Vector of StringsCheck if a Vector Contains the Given ElementCount the Number of Elements in a VectorFind Index of an Element in a VectorAccess Values in a VectorAdd Leading Zeros to VectorR Program to check Armstrong Number
An Armstrong number, also known as narcissistic number, is a number that is equal to the sum of the cubes of its own digits.
For example, 370 is an Armstrong number since 370 = 3*3*3 + 7*7*7 + 0*0*0.
Example: Check Armstrong number
# take input from the user
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)
}
# display the result
if(num == sum) {
print(paste(num, "is an Armstrong number"))
} else {
print(paste(num, "is not an Armstrong number"))
}
Output 1
Enter a number: 23
[1] "23 is not an Armstrong number"
Output 2
Enter a number: 370
[1] "370 is an Armstrong number"
Here, we ask the user for a number and check if it is an Armstrong number.
We need to calculate the sum of cube of each digit. So, we initialize the sum to 0 and obtain each digit number by using the modulus operator %%.
Remainder of a number when it is divided by 10 is the last digit of the number.
We take the cubes using exponent operator. Finally, we compare the sum with the original number and conclude it is an Armstrong number if they are equal.