Sample Exercises
Subroutines: Calculator Recursion
Write a program that uses recursion to compute the total of several numbers with addition and subtraction. It will be given a string like this: "2 + 4 - 3 + 10 - 5". It should first take the first two numbers and their operator, and compute the value, and then replace those numbers with the value and call itself. If there is only one number remaining, it should return that number. So you would produce the result through a process like this:
- 2 + 4 - 3 + 10 - 5
- 6 - 3 + 10 - 5
- 3 + 10 - 5
- 13 - 5
- 8
In other words, it modifies the string containing the formula, replacing the first two numbers with their sum, and calls itself with the modified string (or if you prefer, with a new string that contains the same content) as its argument. This way it can compute the sum of an arbitrarily long sequence of numbers with relatively simple code. (Yes, it can also be written as a loop but for the purpose of this exercise you should use recursion.) And watch out for the base case - make sure the program does not run forever!
Start with this main loop (you can download this file from the "auxiliary files" section below), and add your subroutine recursum (a pun of "recursion" and "sum") to complete the program:
#!/usr/bin/perl -w
use strict;
while(<>){
chomp;
print recursum($_), "\n";
}
The program should take its input from STDIN and print the output to STDOUT. Here is an example of the program's output (user input is underlined):
./lab7p2.plx 2 + 4 - 3 + 10 - 5 8 11 11 4 - 6 + 9 7
Note: Only addition and subtraction need to be supported. All numbers used will be positive integers.
Auxiliary File for Calculator Recursion
Solution for Calculator Recursion
SolutionLast updated:
Copyright © 1995-2008 William R. Ward dba Bay View Training. All Rights Reserved. “Bay View Training”, “Bay View Consulting Services”, “Bay View Software”, the sailboat logo, and the domain name “bayview.com” are trademarks and/or service marks of William R. Ward dba Bay View Training. For more information, contact training@bayview.com
