1.
Exercise Set 1
Exercise 1
Let's begin the lab sessions by finding out how to get Scheme to execute the program
(sqrt 137641)
Open DrScheme as
Start Programs PLT Scheme Dr Scheme.
In the Interactions window -- the lower of the two large text areas -- DrScheme displays a
one-line greeting, a reminder of which dialect of Scheme it expects to see, and a prompt
(in this case, a greater-than sign), indicating that DrScheme is ready to deal with any
command or definition that you type in.
Welcome to DrScheme, version 371 [3m].
Language: Textual (MzScheme, includes R5RS).
>
Move the mouse pointer to the right of the prompt, click the left mouse button, and type
in the program shown above.
Press the ‘Enter’ key after the right parenthesis. At this point, DrScheme examines your
command, translates it into a sequence of instructions for the computer's central
processor, feeds those instructions to the processor, and displays the result. Because this
particular program is extremely simple, the result is printed immediately. When the
processing is complete, the interactions window should look like this:
Welcome to DrScheme, version 371 [3m].
Language: Textual (MzScheme, includes R5RS).
> (sqrt 137641)
371
>
Exercise 2
multiply 162 by 1383
Exercise 3
The Scheme procedure abs computes the absolute value of its argument. Have DrScheme
compute the absolute value of -197.
TCS INTERNAL
2.
Exercise 4
The Scheme procedure for raising a number to some power is expt. Call this procedure to
compute the cube of 19 (that is, the result of raising 19 to the power 3), and again to
compute the nineteenth power of 3.
Exercise 5
Type the correct expressions corresponding to the following expressions
• (2 + 3)
• 7*9
• sqrt(49)
Exercise 6 – A Simple definition
Write a definition that will cause Scheme to recognize dozen as a name for the number 12.
Type it into the Interactions window.
(define dozen 12)
Exercise 7 – Defining a procedure
Write a definition that will cause Scheme to recognize raise-to-power as an alias for expt. (
Note:- write a call to expt function inside the new function)
Exercise 8
After doing exercise 7, move the pointer into the Interactions window, click the left
mouse button, and type in the expression
(raise-to-power dozen 3)
Exercise 9
Type the following Scheme program into the definitions window.
(define area 121)
(define square-root sqrt)
(define side (square-root area))
The last one is a definition with a procedure call inside it; the effect is to have DrScheme
compute the square root of 121 and define side as a name for the result.
TCS INTERNAL
3.
Exercise 10
Have DrScheme compute the result of dividing 103212 by 732. Then have it divide the
same dividend by 564.
Exercise 11
Utopia's tax accountants always use programs that compute income taxes even though the
tax rate is a solid, never-changing 15%. Define the program tax, which determines the tax
on the gross pay.
Also define netpay. The program determines the net pay of an employee from the number
of hours worked. Assume an hourly rate of $12.
Exercise 12
An old-style movie theater has a simple profit function. Each customer pays $5 per ticket.
Every performance costs the theater $20, plus $.50 per attendee. Develop the function
total-profit. It consumes the number of attendees (of a show) and produces how much
income the attendees produce.
Exercise 13
Evaluate the following sentences in DrScheme, one at a time: Read and understand the
error messages
(+ (10) 20)
(10 + 20)
(+ +)
Exercise 14
Enter the following sentences, one by one, into DrScheme's Definitions window and click
Execute:
(define (f 1)
(+ x 10))
(define (g x)
+ x 10)
(define h(x)
(+ x 10))
Exercise 15
Evaluate the following grammatically legal Scheme expressions in DrScheme's Interactions
window:
TCS INTERNAL
4.
(+ 5 (/ 1 0))
(sin 10 20)
(somef 10)
Read the error messages.
Exercise 16
Enter the following grammatically legal Scheme program into the Definitions window and
click the Execute button:
(define (somef x)
(sin x x))
Then, in the Interactions window, evaluate the expressions:
(somef 10 20)
(somef 10)
and read the error messages. Also observe what DrScheme highlights.
Exercise 17
The United States uses the English system of (length) measurements. The rest of the
world uses the metric system. So, people who travel abroad and companies that trade
with foreign partners often need to convert English measurements to metric ones and vice
versa.
Here is a table that shows the six major units of length measurements of the English
system:
1 inch = 2.54 cm
1 foot = 12 in.
1 yard = 3 ft.
1 rod = 5(1/2) yd.
1 furlong = 40 rd.
1 mile = 8 fl.
Develop the functions inches->cm, feet->inches, yards->feet, rods->yards, furlongs->rods, and
miles->furlongs. Then develop the functions feet->cm, yards->cm, rods->inches, and miles->feet.
Develop the functions inches->cm, feet->inches, yards->feet, rods->yards, furlongs->rods, and miles-
>furlongs.
TCS INTERNAL
5.
Then develop the functions feet->cm, yards->cm, rods->inches, and miles->feet.
Hint: Reuse functions as much as possible. Use variable definitions to specify constants.
Exercise 18
Develop the program volume-cylinder. It consumes the radius of a cylinder's base disk and
its height; it computes the volume of the cylinder.
Exercise 19
Develop area-cylinder. The program consumes the radius of the cylinder's base disk and its
height. Its result is the surface area of the cylinder.
Exercise 20
Develop the function area-pipe. It computes the surface area of a pipe, which is an open
cylinder. The program consumes three values: the pipe's inner radius, its length, and the
thickness of its wall.
Develop two versions: a program that consists of a single definition and a program that
consists of several function definitions. Which one evokes more confidence?
Exercise 21
Develop the program height, which computes the height that a rocket reaches in a given
amount of time. If the rocket accelerates at a constant rate g, it reaches a speed of g · t in t
time units and a height of 1/2 * v * t where v is the speed at t.
Exercise 22
Recall the program Fahrenheit->Celsius from the above exercise. The program consumes a
temperature measured in Fahrenheit and produces the Celsius equivalent.
Develop the program Celsius->Fahrenheit, which consumes a temperature measured in
Celsius and produces the Fahrenheit equivalent.
Now consider the function
;; I : number -> number
;; to convert a Fahrenheit temperature to Celsius and back
(define (I f)
(Celsius->Fahrenheit (Fahrenheit->Celsius f)))
Evaluate (I 32).
TCS INTERNAL
6.
Exercise 23
What are the results of the following Scheme conditions?
1. (and (> 4 3) (<= 10 100))
2. (or (> 4 3) (= 10 100))
3. (not (= 2 3))
Exercise 24
What are the results of the following when a) ,x = 4 b) x = 2 c) x=7/2
1. (> x 3)
2. (and (> 4 x) (> x 3))
3. (= (* x x) x)
Exercise 25
Decide which of the following two cond-expressions is legal:
(cond (cond
[(< n 10) 20] [(< n 10) 20]
[(> n 20) 0] [(and (> n 20) (<= n 30))]
[else 1]) [else 1])
Explain why the other one is not. Why is the following illegal?
(cond [(< n 10) 20]
[* 10 n]
[else 555]) ;
Exercise 26
What is the value of
(cond
[(<= n 1000) .040]
[(<= n 5000) .045]
[(<= n 10000) .055]
[(> n 10000) .060])
when n is (a) 500, (b) 2800, and (c) 15000?
TCS INTERNAL
7.
Exercise 27
What is the value of
(cond
[(<= n 1000) (* .040 1000)]
[(<= n 5000) (+ (* 1000 .040)
(* (- n 1000) .045))]
[else (+ (* 1000 .040)
(* 4000 .045)
(* (- n 10000) .055))])
when n is (a) 500, (b) 2800, and (c) 15000?
Exercise 28
Develop the function interest. Like interest-rate, it consumes a deposit amount. Instead of the
rate, it produces the actual amount of interest that the money earns in a year. The bank
pays a flat 4% for deposits of up to $1,000, a flat 4.5% per year for deposits of up to
$5,000, and a flat 5% for deposits of more than Rs.5,000.
Exercise 29
Develop the function tax, which consumes the gross pay and produces the amount of tax
owed. For a gross pay of $240 or less, the tax is 0%; for over Rs. 240 and Rs. 480 or less,
the tax rate is 15%; and for any pay over $480, the tax rate is 28%.
Also develop netpay. The function determines the net pay of an employee from the
number of hours worked. The net pay is the gross pay minus the tax. Assume the hourly
pay rate is Rs.12. Remember to develop auxiliary functions when a definition becomes
too large or too complex to manage.
Exercise 30
Some credit card companies pay back a small portion of the charges a customer makes
over a year. One company returns
1. .25% for the first Rs500 of charges,
2. .50% for the next Rs1000 (that is, the portion between Rs500 and Rs1500),
3. .75% for the next Rs1000 (that is, the portion between Rs1500 and Rs2500),
4. and 1.0% for everything above Rs2500.
Thus, a customer who charges Rs400 a year receives Rs1.00, which is 0.25 · 1/100 · 400,
and one who charges Rs1,400 a year receives Rs5.75, which is 1.25 = 0.25 · 1/100 · 500
for the first Rs500 and 0.50 · 1/100 · 900 = 4.50 for the next Rs900.
TCS INTERNAL
8.
Determine by hand the pay-backs for a customer who charged Rs2000 and one who
charged Rs2600.
Define the function pay-back, which consumes a charge amount and computes the
corresponding pay-back amount.
Exercise 31
Write the contract, purpose, and header for a function that computes the area of a
rectangle given its length and width.
Write three examples for the behavior of this program.
Exercise 32
Develop a function that computes the distance a boat travels across a river, given the
width of the river, the boat's speed perpendicular to the river, and the river's speed. Speed
is distance/time, and the Pythagorean theorem is c2 = a2 + b2.
Exercise 33
Develop a function that computes how long after their deparature two trains will meet.
Assume that the trains travel between two points, along a single section of track, going in
opposite directions. The function should consume the trains' speeds and the starting
distance between the trains. Speed is distance/time.
Exercise 34
Develop a function that when given an initial amount of money (called the principal), a
simple annual interest rate, and a number of months will compute the balance at the end
of that time. Assume that no additional deposits or withdrawals are made and and that a
month is 1/12 of a year. Total interest is the product of the principal, the annual interest
rate expressed as a decimal, and the number of years.
Exercise 35
Develop a function that when given the length and width of a rectangular floor and the
edge length of a square tile will compute the whole number of tiles needed to cover the
floor completely.
Exercise 36
Develop a function that computes the area of a regular polygon given the length of one
side and the number of sides. If n is the number of sides and s is the length of a side, the
area of a regular polygon is equal to 1/4 * n * s2 * 1/(tan PI/n).
TCS INTERNAL
9.
Exercise 37
Develop a function to return the mean of 5 exam scores.
Exercise 38
Develop a function that when given the area of a square will calculate its perimeter.
Exercise 39
Drop a rubber ball from a height h. Each time it hits the ground, the ball bounces up to
2/3 of the height it dropped. Develop a function that computes how far the ball travels by
the time it hits the ground for the third time? Hint: try 36[in] for the initial height.
Exercise 40
Develop the function, total-inches. The function consumes a length represented by two
numbers: the first a number of feet, and the second a number of inches. The function
produces the total length in inches.
Exercise 41
The nation of Progressiva has a simple tax code. The tax you pay is your salary times the
tax rate, and the tax rate is 1/2% per thousand dollars of salary. For example, if you make
$40,000, your tax rate is 1/2% times 40, which is 20%, so you pay 20% of $40,000,
which is $8,000.
Develop a function to compute the net pay (i.e. pay after taxes) of a person with a given
salary. HINT: develop one or two auxiliary functions as well as net-pay.
This tax system has the peculiar feature that, beyond a certain income level, it doesn't pay
to earn any more: for every additional dollar you earn, you have to pay MORE than a
dollar more to the government. Use your net-pay function to find this income level.
Exercise 42
Develop the function, semester-grade. The function consumes two numbers -- the first
representing a cumulative homework score and the other representing the final exam
socre -- and produces the semester grade weighted 80% homework and 20% final exam.
Exercise 43
Develop the function, winning-average. The function consumes two numbers
representing the number of wins and losses and produces the winning average where
1000 would be equivalent to 100 percent.
TCS INTERNAL
10.
Exercise 44
1. Write a contract for a function that finds the number of inches in a given number
of feet.
2. Write a purpose and contract for a function (operation) that finds the gas
consumption (miles per gallon) for a particular vehicle.
3. Write a purpose and contract for a function that computes the slope of a line if the
change in y-value and the change in x-value are given.
4. Write the purpose, contract and two examples for a function that consumes the
length, width, and depth of a tank and produces its volume.
5. Write the purpose, contract, two examples, and header for a function that
consumes five quiz grades for a student and produces the quiz average.
6. Write the purpose, contract, two examples, the header and the body for a function
that consumes the amount of money a family spends on groceries per week and
that computes the yearly cost of groceries for that family.
Exercise 45
Ms. Sis Y. Fuss wants to push a rock up a hill. The distance is d yards. In one minute, she
pushes the rock 30 yards, but then it slides down 4 yards. When she has reached d yards,
it won't slide down anymore. How many (entire) minutes will it take her?
Exercise 46
Generate the Fibonacci sequence. Starting with 0, 1 add them up then take the result and add it to the last
number and repeat.
Answer should look like:
0 1 1 2 3 5 8 13 21 34 55 89
144 233 377 610 987 1597 2584 4181
Exercise 47
Functions - write a program that calls bignum() and littlenum() which determine, respectively, the highest
and the smallest of a sequecnce of numbers read in from the terminal.
Exercise 48
Write a program to sort exactly three numbers
Exercise 49
Write a program to reverse the digits of an integer number stored in the computers memory and write the
number and its reverse to the screen.
TCS INTERNAL
11.
Exercise 50
Compute the factorial defined by the rule n! = n * (n - 1) *….* 2 * 2 * 1. Test your routine for values of n =
1; 2; 3,…… 50. What do you observe?
Exercise 51
Write a program to find all the factors of a non-negative integer?
Exercise 52
Write a program to determine if a given input non-negative integer is prime?
Exercise 53
Perfect Numbers. A number P is said to be perfect if P is equal to the sum of all its factor excluding itself.
Example, 28 is perfect. Using the definition of perfect number, find all the perfect numbers in a range of
numbers
Exercise 54
Consecutive Primes. Two consecutive odd numbers that are also prime are called consecutive
primes. Write a program to look for all consecutive primes in a range. . Write a program to find out (the
hard way, by counting them) how many of the numbers from 1 to 10 are greater than 3. (The answer, of
course, should be 7.)
Exercise 55
Write a program to compute the average of the ten numbers 1, 4, 9, ..., 81, 100, that is, the average of the
squares of the numbers from 1 to 10
Exercise 56
Write a program to print the numbers between 1 and 10, along with an indication of whether each is even or
odd, like this:
1. 1 is odd
2. 2 is even
3. 3 is odd
4. ...
Exercise 57
Write a program to print the first n positive integers and their factorials. (The factorial of 1 is 1, the
factorial of 2 is 1 * 2 = 2, the factorial of 3 is 1 * 2 * 3 = 6, the factorial of 4 is 1 * 2 * 3 * 4 = 24, etc.)
TCS INTERNAL
12.
Exercise 58
Write a square() function and use it to print the squares of the numbers 1-10
Exercise 59
Write a program to read its input, one line at a time, and print each line backwards. To do the reversing,
write a function to reverse a string, in place.
Exercise 60
Write a program that will read in a year and report if it is a leap year.
A leap year occurs: on every year that is evenly divisible by 4 except every year that is evenly divisible by
100 except every year that is evenly divisible by 400.
Exercise 61
Write a program that will read in a number from 0 to 9 and spell out that number. The program must also
report any values that are out of range.In other words, for an input say 2, output should be two
Exercise 62
There once was a wise servant who saved the life of a princess. The king promised to pay whatever the
servant could dream up. Knowing that the king loved chess, the servant told the king he would like to have
grains of wheat. One grain on the first square of a chess board. Two grains on the next. Four on the third,
and so on. There are 64 squares on a chessboard.
Write a program that shows how many grains were on each square and the total number of grains.
In other words, I want to type >Grains
and see
square 1: 1 grain
square 2: 2 grains
square 3: 4 grains
square 4: 8 grains
Exercise 63
If you have N eggs, then you have N/12 dozen eggs, with N%12 eggs left over. (This is essentially the
definition of the / and % operators for integers.) Write a program that asks the user how many eggs she has
and then tells the user how many dozen eggs she has and how many extra eggs are left over.
A gross of eggs is equal to 144 eggs. Extend your program so that it will tell the user how many gross, how
many dozen, and how many left over eggs she has. For example, if the user says that she has 1342 eggs,
then your program would respond with
Your number of eggs is 9 gross, 3 dozen, and 10
TCS INTERNAL
13.
since 1342 is equal to 9*144 + 3*12 + 10.
Exercise 64
A microwave oven manufacturer recommends that when heating two items, add 50% to the heating time,
and when heating three items double the heating time. Heating more than three items at once is not
recommended.
Write a program that asks the user for the number of items and the single-item heating time. The program
then writes out the recommended heating time.
Hint: do this with four successive single-branches if statements each of which tests for one of the four
cases: 1 item, 2 items, 3 items, more than three items. Look at the sports car purchase program in the
chapter to see how to do this, if you are stuck
Exercise 65
Sam and Ella's Delicatessen wants a program to take orders from the internet. The program will ask what
item the user wants, will ask its price, and will ask if the user wants overnight shipping. Regular shipping
for items under $10 is $2.00; for items $10 or more shipping is $3.00. For overnight delivery add $5.00.
Enter the item:
Tuna Salad
Enter the price:
450
Overnight delivery (0==no, 1==yes)
1
Invoice:
Tuna Salad 4.50
shipping 7.00
total 11.50
Exercise 66
Write a recursive program that finds the greatest common denominator GCD.
Exercise 67
Write a recursive program that finds the least common multiple LCM.
Exercise 68
Two positive integers are friendly if each one is equal to the sum of the divisors (including one and
excluding the number itself) of each other. 220 and 284 are friendly. Write a program to check if two
numbers are friendly.
Exercise 69
Write a procedure subword that takes three arguments: a word, a starting position, and an ending position
number. It should return the subword containing only the letters between the specified positions.
TCS INTERNAL
14.
Exercise 70
Develop a function that computes the area of a regular polygon given the length of one
side and the number of sides. If n is the number of sides and s is the length of a side, the
area of a regular polygon is equal to 1/4 * n * s2 * 1/(tan PI/n).
TCS INTERNAL
Clipping is a handy way to collect and organize the most important slides from a presentation. You can keep your great finds in clipboards organized around topics.