Write a shell program to find the sum of alternate digits in a given 5-digit number | Unix Linux Forums | Shell Programming and Scripting

 Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts and shell scripting languages here.

# Write a shell program to find the sum of alternate digits in a given 5-digit number

## Shell Programming and Scripting

#1
10-29-2006
 banta Registered User Join Date: Oct 2006 Last Activity: 29 October 2006, 4:29 PM EST Posts: 1 Thanks: 0 Thanked 0 Times in 0 Posts
Write a shell program to find the sum of alternate digits in a given 5-digit number

Hi Can any one please post the answer for the above program..................

Last edited by banta; 10-29-2006 at 04:28 PM.. Reason: Wrong question
#2
10-29-2006
 vgersh99   Forum Advisor Join Date: Feb 2005 Last Activity: 18 April 2014, 8:49 AM EDT Location: Foxborough, MA Posts: 7,523 Thanks: 137 Thanked 534 Times in 502 Posts
banta.sh 28462

banta.sh:

Code:
```#!/bin/ksh

a="\${1}"

typeset -i i=1

while (( i <= 5 ))
do
((num=\$(echo "\${a}" | cut -c "\${i}") ))
if (( i == 1 )); then
printf "\$num"
else
printf "+\$num"
fi
((sum=sum + num))
((i=i+2))
done

printf "=\${sum}\n"```

#3
10-29-2006
 ghostdog74 Registered User Join Date: Sep 2006 Last Activity: 7 November 2013, 6:42 AM EST Posts: 2,651 Thanks: 0 Thanked 16 Times in 16 Posts
Python alternative

Code:
```#!/usr/bin/python
a = 12345
b = list(str(a))
print sum( map(int,b[::2]) )```

output:

Code:
`9`

#4
10-30-2006
 rajnikanth.1912 Registered User Join Date: Oct 2006 Last Activity: 6 June 2007, 5:50 AM EDT Posts: 5 Thanks: 0 Thanked 0 Times in 0 Posts
You need to initialise the variables num and sum

#!/bin/ksh

a=12346
b=`expr length \$a`
echo " length : \$b"
typeset -i i=1
num=0
sum=0
while (( i <= \$b ))
do
((num=\$(echo "\${a}" | cut -c "\${i}") ))
if (( i == 1 )); then
printf "\$num"
else
printf "+\$num"
fi
((sum=sum + num))
((i=i+2))
done
printf "=\${sum}\n"
~

-------
length : 5
1+3+6=10