R Program to Check for Armstrong Number

1. Introduction

An Armstrong number (or narcissistic number) is a number that is equal to the sum of its own digits raised to the power of the number of digits. For instance, 153 is an Armstrong number because (1^3 + 5^3 + 3^3 = 153).

2. Program Overview

Our R program will:

1. Prompt the user to input a number.

2. Check whether the given number is an Armstrong number.

3. Display the result to the user.

3. Code Program

# Prompt user for input
num <- as.numeric(readline(prompt = "Enter a number: "))

# Check if a number is an Armstrong number
is_armstrong <- function(num) {
  digits <- as.numeric(unlist(strsplit(as.character(num), "")))
  n <- length(digits)
  sum_of_powers <- sum(digits^n)
  return(sum_of_powers == num)

# Check and display the result
if (is_armstrong(num)) {
  cat(num, "is an Armstrong number.")
} else {
  cat(num, "is not an Armstrong number.")


For input 153, the output will be:
"153 is an Armstrong number."

4. Step By Step Explanation

1. User Input: The program begins by prompting the user to enter a number which is stored in the num variable.

2. Digit Extraction: The function is_armstrong splits the number into its individual digits and computes the number of digits (n).

3. Armstrong Check: It then raises each digit to the power of n and sums them up. If the result is equal to the original number, it is an Armstrong number.

4. Result Display: Finally, the program prints out whether or not the input number is an Armstrong number.