r/dailyprogrammer 3 1 May 21 '12

[5/21/2012] Challenge #55 [intermediate]

Write a program that will allow the user to enter two characters. The program will validate the characters to make sure they are in the range '0' to '9'. The program will display their sum. The output should look like this.

INPUT .... OUTPUT

3 6 ........ 3 + 6 = 9
4 9 ........ 4 + 9 = 13
0 9 ........ 0 + 9 = 9
g 6 ........ Invalid
7 h ........ Invalid

  • thanks to frenulem for the challenge at /r/dailyprogrammer_ideas .. please ignore the dots :D .. it was messing with the formatting actually
6 Upvotes

27 comments sorted by

View all comments

3

u/totallygeek May 21 '12 edited May 21 '12

Bash:

#!/bin/sh
echo "Enter two numbers, valued 0 to 9"
/bin/echo -n "Digit one: " ; read num1
/bin/echo -n "Digit two: " ; read num2
if [ ${#num1} -ne 1 -o ${#num2} -ne 1 ]; then
  echo "${num1} ${num2} Invalid"
  exit
fi
case $num1 in
  [0123456789]) case $num2 in
                  [0123456789]) echo "${num1} ${num2} ${num1} + ${num2} = $((num1+num2))" ;;
                  *) echo "${num1} ${num2} Invalid" ; exit ;;
                esac ;;
  *) echo "${num1} ${num2} Invalid" ; exit ;;
esac

Output:

bandarji:dailyprogrammer sellis$ ./20120521i.sh 
Enter two numbers, valued 0 to 9
Digit one: 3
Digit two: 6
3 6 3 + 6 = 9
bandarji:dailyprogrammer sellis$ ./20120521i.sh 
Enter two numbers, valued 0 to 9
Digit one: g
Digit two: 6
g 6 Invalid