An Armstrong number is a number that is equal to the sum of cubes of its digits. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153.
This article will explain how to create a shell script to check if a number is an Armstrong number.
What is a Shell Script?
A shell script is a program written in a shell programming language that can be executed in Unix and Unix-like operating systems. These scripts allow for command execution, usually from the system shell, which allows for programming commands as well as direct command entry.
Shell scripts can automate tasks, manage system resources, and perform system level programming.
Checking Armstrong Number using a Shell Script
We can write a shell script to check if a number is an Armstrong number using the following steps:
- Read the number to check for Armstrong number.
- Calculate the length of the number (the number of digits).
- For each digit in the number, compute the digit’s power with the total count of digits, and add the result to the sum.
- If the sum of these computations is equal to the original number, then it’s an Armstrong number.
Below is a shell script example that checks if a given number is an Armstrong number:
To execute the script, save it to a file (for example, “armstrong.sh”), then run the script in a Unix or Unix-like environment with the command bash armstrong.sh. The script will prompt you to enter a number, and then it will tell you whether or not the number is an Armstrong number.
Understanding the Script
- The script begins with the shebang (#!/bin/bash) to indicate that the script should be run using bash shell.
- The length() function calculates the number of digits in a number by continually dividing the number by 10 until it becomes 0, incrementing a length counter at each step.
- The check_armstrong() function calculates the Armstrong number. It starts by calculating the length of the number, then iteratively takes each digit in the number, raises it to the power of the number’s length, and adds it to the sum. If the sum equals the original number, the function prints that the number is an Armstrong number; otherwise, it prints that it’s not.
- Finally, the script reads a number from the user and calls the check_armstrong() function with the entered number.
This script demonstrates how shell scripting can be used for mathematical and logic-based programming tasks. It provides a clear, command-line interface to interact with the user, perform calculations, and provide output based on logic and conditions.