So far you have only written single function definitions or straight-line programs. It is important to be able to put several things together into a program.
A program can contain a collection of function definitions, if you want them, and a sequence of commands for the program to perform when it runs. To build a Cinnameg program, do the following.
Write the word Define in front of each function definition, and write %Define after it. Put the function definitions one after another, with a blank line between them.
Order the function definitions so that each function is defined before it is used. An exception is that a function can use itself.
Write the word Execute in front of the sequence of commands that you want the program to perform, and write %Execute at the end.
Here is a program that writes the greatest common factor of two numbers a and b.
Define gcf(x: Integer, y: Integer): Integer by case gcf(x,y) = y when x == 0 case gcf(x,y) = gcf(y `mod` x, x) %Define Execute Let a = 120. Let b = 75. Display "The greatest common factor of ". Display a. Display " and ". Display b. Display " is ". Display gcf(a,b). Display "\n" %Execute
[solve] Write a program that defines the factorial function and that shows factorial(10).
[solve] Write a program that contains two function definitions. Include a definition of the factorial function. Then add another definition after it of function sumFactorials(n), which produces the sum 1! + 2! + 3! + ... + n!. For example, sumFactorials(3) = 1! + 2! + 3! = 1 + 2 + 6 = 9 and sumFactorials(4) = 1! + 2! + 3! + 4! = 1 + 2 + 6 + 24 = 33. Then make the program display the values of sumFactorials(3) and sumFactorials(5). (Remember that the definition of sumFactorial can use your factorial function.)
[solve] What if you define a function that is not used? Will the function be used automatically for you when its definition is encountered?
To build a complete Cinnameg program, write Define ... %Define around each function definition and write Execute ... %Execute around the steps to be performed.
A command is called a statement.
A Let-statement computes a value and gives it a name.
A Display-statement computes a value and displays it on the console.