Procedures
What is a procedure? Often in a program we will need to repeat the same task over and over again. Rather than repeat writing the code every time we use it, we can use what is called a procedure.
Consider our quiz program where we might wish for our user to click a continue button after each question. That means every question we ask we need to draw the box: drawfillbox(50,50,150,100) locatexy(75,75) put(“continue”)
Then after they answer the question, we need to check whether they have clicked the button: loop mousewhere(x, y, button) exit when x<150 and x >50 and y >50 and y<100 and button=1 then end loop
If we are asking only one or two questions, repeating this code is fine. But if we intend to ask 30-50 questions, then this isn’t the best way to do things.
A procedure is essentially a small program within a program, that we will call whenever it is needed. A procedure is created to perform a very limited and specific task. In our example we would create two procedures. The first to create the button, and the second to check whether the button was pressed.
Syntax Just as we declare a variable in order for the program to recognize it later, we must also declare a procedure: procedure name ( parameters ) instructions end name Then when we wish to use the procedure in our program we call it by it’s name.
Example procedure create_button drawfillbox(50,50,150,100,blue) locatexy(75,75) put(“continue”) end create_button
procedure is_continue_clicked loop mousewhere(x, y, button) exit when x<150 and x >50 and y >50 and y<100 and button=1 then end loop end is_continue_clicked
Now our program will look like: put “What is your name” get name create_button is_continue_clicked put “What is your age” get age createbutton
Special notes on procedures Procedures must be declared at the beginning of the file! You may call a procedure within a procedure but it must have already been declared. (See example B) Two or more procedures may not call each other!
Example B procedure terrence put “Hi my name is Terrence” end terrence procedure philip terrence put “Hi Terrence my name is Philip” end philip
Example C procedure one two % calls procedure two end one % but two hasn’t been % declared yet procedure two one % calls procedure one end two