Home
Intro
LC
ACR
About

Day 5 - Procedures and Functions

-=-=-=-=-=-=-=-=-=-=-

What you are going to learn today:

  • What procedures and functions are
  • What's scope of variables
  • How to implement procedures and functions
  • And an example program to round it all up

-=-=-=-=-=-=-=-=-=-=-

Procedures and functions are the topics today, so listen up! After going through this tutorial, you will never want to give up programming again!

What are Procedures and Functions?

Procedures? Functions? What? Is this some sort of calculator manual? No, procedures and functions are a feature of Pascal which allow you to repeat a certain piece of code or calculation again and again. Isn't that great? But first, we must find out what procedures and functions are in reality.

Main Program Sequence -> Procedure -> Main Program Sequence

First of all, what is a procedure? Well, let's say you've got a job as a dishwasher. The process of washing a dish could be:

  1. Dip the dish into the water
  2. Cover every inch of the dish with soap
  3. Rinse and dry the dish
So, every time you need to wash a dish, you do just that. Dip, soap, dry. Dip, soap, dry. Dip, soap, dry. Even when you go home, you dip, soap, dry. Dip, soap, dry. It's the same sequence! A procedure works the same way. When people give you instructions, they tell you to "wash the dishes", not "dip, soap, then dry". This is because you already know what is involved when you wash dishes. A procedure is just a faster, and more modular way, to get the job done. By replacing a stack of instructions with one single statement, if makes code easier to read and debug.

Main Program Sequence -> Function -> 6 -> Main Program Sequence

Now about functions. A function is just like a procedure except that it returns a value. For example, somebody may ask you to count the number of chairs in a hall. You first step in, count, then return the number of chairs in the hall back to the person who first asked you. That is a function. A function simply returns another value back into the program, such as complex calculation results, the position of the mouse cursor, or the number of times an atomic bomb had dropped onto the Earth. Functions can report almost anything. Numbers, strings, characters, anything! And if you want to, you can use functions replace procedures completely! Isn't that great?

Scope of Variables

Procedures and functions are 'stacked' Now that you understand the concepts, let's be honest. Everything good in life has a catch. Procedures and functions are no different, and this catch is the concept of scope. To understand this concept, visualise a stack of exercise books on your table. Everytime you call a procedure or a function, it will be placed at the top of the stack. When the procedure or function finishes, it is removed. Now, when a procedure and function goes, everything else declared in it goes too! That means that if you declare a variable in procedure x, you can't use that variable in procedure y! The variable simply goes poof, and disappears into a mist of sparkling electronic dust. However, you can use variables which were declared in lower procedures and functions in the stack. Unbelievable! Confusing, maybe, but very powerful...

How procedures and functions are implemented

How are procedures and functions implemented? Well, here's the low-down on the syntax for declaring your very own procedures and functions.

Procedures are declared using the procedure keyword, as you can see below. The name of the procedure comes first, followed by a semicolon, then the contents of the procedure.

  procedure WhyMe;

    var
      i: integer;

    begin
      for i := 1 to 10
        Writeln('Why Me?!');
    end;
A procedure is just like a separate program in itself. You can declare variables and use them within your program code. However, as described above, after the procedure ends, the variables vapourize with it. So, now that you have declared a procedure. How do you call it? Ahh, this is easy. Just type in the name of the procedure. What else could be easier?
  begin
    WhyMe;
    Writeln('That was my true feelings regarding Exams');
  end.
When this program executes, it will print 10 "Why Me?!"s and print the final message "That was my true feelings regarding Exams". After a procedure finishes, it returns back to place where it was called. Isn't that smart? Pretty innovative.

Functions, on the other hand, cannot be used just like that because they return a value back to the program instead of just doing things. For instance, we may have a function which acts like this:

  function AddEmUp : integer;
    begin
      AddEmUp := a + b + c;
    end;
This function will return the sum of a, b, and c. Well, how does it work? The function name comes after the keyword 'function'. After the function name, you get the data type the function should return. Huh? Yes, even when using functions, you can't run away from the nearly limitless list of data types. The value the function should return is assigned to the name of the function. In this case, because the name of the function is 'AddEmUp', we assign the result of the function to the same name! How do you use functions then? Well...
  begin
    a := 5;
    b := 9;
    c := 4;
    Writeln(AddEmUp);
  end.
This program will print out the sum of a, b, and c! Marvellous use of functions, isn't it? Well, it isn't finished yet!

x - 2, y - 3, z - 5

Procedures and functions would have been dreadfully boring and unflexible if it wasn't for a great feature called parameters. You can use parameters to pass values to the procedure or function to use. For example:

  function AddEmUp2( x, y, z: integer ) : integer;
    begin
      AddEmUp2 := x + y + z;
    end;
Then, to use this function, you must provide values for x, y, and z. This is done by using brackets.
  begin
    Writeln(AddEmUp2(2, 3, 5));
  end.
In this example, x would be 2, y would be 3, and z would be 5. You're passing values over for the procedure or function to make use of. Got the idea? No? Well, here's another example.
  procedure PrintEm( x, y, z: integer );
    begin
      Writeln(x);
      Writeln(y);
      Writeln(z);
    end;
If you pass the values 2, 3, and 5, this procedure would print out those numbers. That's great! Now you can provide information to the program on the fly. Power on the go...

The final example program...

Here it is, in its full glory, the example program of the day! Buckle up, and enjoy typing this utterly simple yet powerful program.

Type

1: program AddEmUpAgain;
2:
3:   function AddEmUp( a, b, c: integer ) : integer;
4:     begin
5:       AddEmUp := a + b + c;
6:     end;
7:
8:   procedure PrintIt( a, b, c: integer );
9:     begin
10:      Writeln('The sum of a, b, and c is ', AddEmUp(a, b, c), '.');
11:    end;
12:
13:  begin
14:    PrintIt(2, 3, 4);
15:  end.

Run

The sum of a, b, and c is 9.

Analyse

Although it looks complicated, this is actually a very simple program. It does absolutely nothing but to add three numbers together! Is that dumb or what?

  • Line 3 - This declares the function AddEmUp, which takes three parameters and adds them up.
  • Line 5 - The only line of AddEmUp, it justs returns the sum of parameters a, b, and c.
  • Line 8 - Declares procedure PrintIt, which also accepts three parameters.
  • Line 10 - This line simply prints out the correct message by calling AddEmUp and passing it the three parameters.
  • Line 14 - This single line starts the whole ball rolling!

Well, that was the great example program of the day! But this topic is far from over. Here are the tips and rules we couldn't fit into the text without making it ridiculously boring. (As if it wasn't already...)

  1. You must declare a function or a procedure before it is used. For example, in the example program above, you can't just put the procedure on top of the function because PrintIt needs to use AddEmUp, it needs to be declared first.
  2. However, if the world somehow gives you a reason to use a procedure before you declare it, you can use the forward keyword. Find out from your nearest F1 key!
  3. What happens if you provide more parameters than a procedure or function needs? Well, when you do so (or vice versa), the compiler simply gives you an error, so go on and experiment! (Em, don't play too much though...)
  4. No, you can't re-declare constants in a new procedure - Why would you anyway?
  5. Procedures and functions are a very important part of structured programming. Suffice it to say that is you don't learn structured programming now, you'll never make it big in the future.
  6. No, there will not be another Bill Gates analogy for this tutorial.
There's a lot more - but hey, this is for beginners right? So, that's it, the list of important things for procedures and functions! Ahh, now you know why people invented lists...

The Final Chapter is coming

Joy! Rapture! Divinity! (Get the joke?) Day 5 is finally over and you can go on to Day 6 - Comments and Other Neat Stuff. Neat Stuff? What neat stuff?! Well, find out for yourself. Avé!

-=-=-=-=-=-=-=-=-=-=-

HomeIntroLCACRAbout
Back to Class B

-=-=-=-=-=-=-=-=-=-=-

This page is ThinkQuest entry 11127.
email: tq97-11127@advanced.org