Day 5
This is the day 5 page for computer programming course 101, an introduction to computer programming. Day 5 is the first of two parts on the topic of functions.Below are the topics and course materials we are learning today.
Procedures and Functions
Procedures and functions, referred to collectively as routines, are self-contained statement blocks which can be called from different locations in a program. A function is a routine that returns a value when it executes. A procedure is a routine that does not return a value.Function calls, because they return a value, can be used as expressions in assignment statements. For example:
S := UpperCase(BookTitle);Calls UpperCase and assigns the result to S. Note that function calls cannot appear on the left side of an := assignment statement.
Procedure calls and function calls be used as complete statements. For example:
ShowMessage(Error);Calls the ShowMessage routine. If ShowMessage is a function, its return value is discarded.
Routine Arguments
Routines can have zero or more arguments. Arguments to a routine are specified by the caller through an opening parenthesis, a list of values seperated by zero or more commas, and a closing parenthesis. For example:
MoveTo(X, Y);Calls the MoveTo routine passing two arguments X and Y. If a routine take no arguments then the parenthesis is optional. For example:
Maxmimize(); Maxmimize;Are both valid ways to invoke the routine named Maxmimize if it has no arguments.
Declaring Your Own Procedures and Functions
Often times when writing programs you'll encounter situations where to want to often a block of logic you've written. Procedures and functions serve this purpose, to provide a mechanism to isolate and reuse pieces of code you've create that are helpful in creating more complex programs. They also simply your work as a programmer by reducing the number of lines in your source code, as well as providing a means to store clean bug free logic.When you declare a procedure or function, you specify its name, the number and type of parameters it takes, and, in the case of a function, the type of its return value. Then you write a block of code that executes logic to match the name you've chosen for your the procedure or function.
A function is declared like so:
function FunctionName(ArgumentList): ReturnType; begin Statements; end;Where FunctionName is any valid identifier, ReturnType is a known type name, and Statements is a sequence of one or more statements to execute when the function is called. ArgumentList is optional and if omitted then the parenthesis are optional as well.
Here is an example of a function:
function IntegerToString(Value: Integer): string; var S: string; I: Integer; begin S := ''; I := Abs(Value); repeat S := Chr(I mod 10 + Ord('0')) + S; I := I div 10; until I = 0; if Value < 0 then S := '-' + S; Result := S; end;This function is identified by the name IntegerToString. It has a single argument of type Integer and returns a string. Before the statements begin you may declare variables for use within the routine. These variables are temporary and are only visible to statements within the IntegerToString routine. This type of visibility to variables within a routine is often known as scope. Functions have a access an implicit variable named Result. The Result variable in a function matches the return type and is used to store the value returned to the function caller.
The statements inside functions and procedures can call other routines. In our implementation of IntegerToString we are calling the Abs, Chr, and Ord routines. We are also using assignments, looping statements, and conditional branching statements.
After we have defined our IntegerToString function, we can use it elsewhere in code like so:
ShowMessage('There are ' + IntegerToString(Minutes) + ' left until the server must reboot');After a procedure or function exits, either by reaching the end of the routine or by use of the Exit function, program control is returned back to the position from whence it was called.
Application: Spreadsheet
The instructor walks the student through the spreadsheet example application. We add password protection to the main form, preventing unauthorized viewing of our propriety company data.Built In Procedures and Functions
The Free Pascal language provides many built in procedures and functions. In this section we'll introduce a few of them. As a computer programmer you're going to have to memorize both the names and use of many routines in order to write anything useful. Try out each of these routines and commit them to your memory.Flow Control and Type Routines
The following routines can be used to either control the flow of you program or return information related to a type.Break Continue Exit Default SizeOf Low High
procedure Break;The Break procedure stops the current loop and returns control to the first statement after the current looping statement. If a loop is nested the Break exits the current loop and returns control to the next outer most loop. As the Break procedure is meant to control looping statement it is a special procedure and its placement is restricted to being used within a looping statement.
procedure Continue;The Continue procedure causes the current to prematurely return control back to the top of the loop. If a loop is nested Continue returns control to the start of the current. Like the Break procedure Continue is also restricted to being used only within a looping statement.
procedure Exit; overload; procedure Exit(R: ResultType); overload;The Exit procedure stops execution of the current routine returning control back to the calling statement. The Exit procedure may optionally specify a result value if it is used within a function.
function Default(V: VariableType): VariableType; overload; function Default(VariableType): VariableType; overload;The Default function returns the default value of a variable or a type. A default value of a type is the same as a blank value. For a Byte the default value is 0. For a string the default value is '' an empty string. For a Char the default value is #0.
function SizeOf(T: TypeName): Integer; overload; function SizeOf(TypeName): Integer; overload;The SizeOf function returns an the size in bytes of a the memory used by a variable or type.
function Low(Ordinal: OrdinalType): OrdinalType; overload; function Low(OrdinalType): OrdinalType; overload;The Low function returns smallest value a variable or type. Note that the return type matches type given in the argument. For example Low(Boolean) returns False, while Low(Byte) returns 0.
function High(O: OrdinalType): OrdinalType; overload; function High(OrdinalType): OrdinalType; overload;The High function returns largest value a variable or type. Note that the return type again matches type given in the argument. The result of High(False) is True and High(Byte) is 255.
Command Line Routines
The following are routines useful when working with the terminal or a command line.ReadLn WriteLn ParamCount ParamStr
procedure ReadLn(var C: Char); overload; procedure ReadLn(var S: string); overload; procedure ReadLn(var I: Integer); overload; procedure ReadLn(var F: Float); overload;The ReadLn procedure reads a text from a terminal and saves it into a variable. If the text typed by the user does not convert into the associated type an exception is raised.
procedure WriteLn; overload; procedure WriteLn(T: InstrinsicType); overload; procedure WriteLn(T1: InstrinsicType; T2, T3, ...); overload;The WriteLn procedure writes a line a text to the terminal. If no arguments are passed a blank line is written. Any number of arguments can be used as long as they are intrinsic types.
function ParamCount: Integer;The ParamCount function returns the number of parameters passed to your program when it was started. Command line parameters are typically separated by spaces, but space character can be enclosed in " quotes turning multiple parameters into a single parameter.
function ParamStr(const S: string): string;The ParamStr function returns the string value of a parameter passed to you program on the command line. The first parameter is indexed by the value 1, the second by 2, and so on. The 0 indexed parameter is the full path and name of your program.
String Related Routines
These routines are helpful when using strings.Chr Ord Length SetLength Space
function Chr(I: Integer): Char;The Chr function convert a number to a character. Numeric character values map unto the standard ASCII code for characters. For example the character returned for Chr(32) is ' ' and Chr(65) returns 'A'.
function Ord(C: Char): Integer; overload; function Ord(O: OrdinalType); Integer; overload;The Ord function converts either a character or an ordinal type to an integer value. For example Ord('A') returns 65 and Ord(True) returns 1.
function Length(const S: string): Integer;The Length function returns the number of characters in a string. For example Length('Hello World!') returns 11 and Length(S) returns the number of characters in S.
procedure SetLength(var S: string; L: Integer);The SetLength procedure alters the length of a string. This procedure is useful if you know the final length your string and want to change it directly.
function Space(N: Integer): string;The Space function returns a string made up of N space characters.
Integer Related Routines
The following routines are useful when working with integer numbers.Abs Inc Dec Odd Round Trunc Random
function Abs(I: IntegerType): IntegerType; overload; function Abs(F: FloatingType): FloatingType; overload;The Abs function returns the absolute value of an integer or floating point number. The absolute value removes any negative sign in front of a number.
function Inc(I: IntegerType): IntegerType;The Inc function increases the value of I by 1.
function Dec(I: IntegerType): IntegerType;The Dec function decreases the value of I by 1.
function Odd(I: IntegerType): Boolean;The Odd function returns True if I is an odd number otherwise it returns False.
function Round(F: FloatingType): Integer;The Round function rounds a floating point number up or down to the nearest integer value.
function Trunc(F: FloatingType): Integer;The Trunc function removes the fractional part of a floating point number as returns the integer part.
function Random(Range: Integer): Integer; overload; function Random: Double; overload;The Random function returns a random number. If a Range is given it returns a integer value I in the range of 0..Range - 1. If no argument is given Random returns a floating point in the range of 0..1.
Floating Point Related Routines
The following routines are useful when working with floating point numbers.Sqrt Sin Cos Tan Int Frac
function Sqrt(N: Double): Double;The Sqrt function returns the square root of N.
function Sin(N: Double): Double;The Sin function returns the sine of N.
function Cos(N: Double): Double;The Cos function returns the cosine of N.
function Tan(N: Double): Double;The Tan function returns the tangent of N.
function Int(N: Double): Double;The Int function returns the integer portion of a floating point value.
function Frac(N: Double): Double;The Frac function returns the fractional portion of a floating point value.
Homework
Scrabble is a popular word board game where players lay down wooden tiles to spell words taken from the English language. Given the following distribution of letter points, write a program to the total score of a letters in a word for the game of Scrabble.1: A, E, I, O, U, L, N, S, R, T 2: D, G 3: B, C, M, P 4: F, H, V, W, Y 5: K 8: J, X 10: Q, ZThe final program should be based on this project and must meet these requirements:
- You must write a routine to calculate the score of words when the score button is pressed
- Both the current score and the highest score must be displayed in the score label
- The project folder should be compressed with 7z and the name must be course101-day005.7z
- The compressed project file must be uploaded to your cloud file account
7za x filename.7zYou can create a 7z archive of a folder from the command line using the syntax:
7za a filename.7z foldername