Shell script to read 5 digit number and calculate the sum of digit
Posted in Shell Math
#!/bin/bash # Shell script to read 5 digit number and calculate the sum of digit # ------------------------------------------------------------------------- # Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/> # This script is licensed under GNU GPL version 2.0 or above # ------------------------------------------------------------------------- # This script is part of nixCraft shell script collection (NSSC) # Visit http://bash.cyberciti.biz/ for more information. # ------------------------------------------------------------------------- echo -n "Enter numnber : " read n # find out length of string using wc -c command len=$(echo $n | wc -c) # remove \n i.e. new line character len=$(( $len - 1 )) # use loop to go throug all digit one by one and calculate sum of digit on fly for (( i=1; i <= $len; i++ )) do sum=$(( $sum + $(echo $n | cut -c $i) )) done echo "Sum of $n is $sum"
Download - Email this to a friend - Printable version
Related Other Helpful Shell Scripts:
- Shell program to read a number and find the sum of digits
- Shell program to calculate the number of digits in a number read from the user
- Shell script to read a character (upper or lower), digit, special symbol and display message according to the character entered
- Shell program to read a number and reverse the number
- Shell script to find whether an input number is palindrome or not
Leave a Reply
We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!
Tags: bash shell script, cut command, digit number, for command, for loop, mathematics, shell loops, shell pipes ~ Last updated on: April 4, 2008

