Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [tutorial] Procedures + Functions + Processes
Index -> Programming, Turing -> Turing Tutorials
Goto page 1, 2  Next
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Tony




PostPosted: Thu Mar 20, 2003 6:45 pm   Post subject: [tutorial] Procedures + Functions + Processes

We all start learning programming in a linear way. Code is executed line after line after line. We can usually skip some lines with an if statement or go back a few with a loop... Remember doing all those flowcharts? Take a look at them; they are all a line from top to bottom (for exceptions of few if statements that have some lines running parallel, but still merging back together).

Linear programming used to be enough, but not always. You want your programs to be dynamic, and have code executed whenever its needed, not when the logic reaches certain point on your 1 way flowchart.

The Solutions:

A)

Procedure
Procedure is a part of the code that can be called upon at any given time. If you have a certain code repeat within the program, it's a good idea to put it inside a procedure as it will use up less resources.

code:

procedure speak()
put "hello"
end speak

speak() %<this line calls the procedure speak which was declared above


This is a very simple example, but if for example you make a procedure with code to save your game status, then you can save your game at any moment, not when the logic of flow chart reaches a certain point.

Function
Function works much like a procedure, but it returns a value. What I mean is that function is like a variable, but it calculates its own value.

code:

function sum() :int
var total:int
total := 1+2
result total
end sum

put sum()


here sum() is treated as a variable which has a value of result (not to confuse with return which will terminate the program). In this case it's 3.

Process
Process works identical to procedure, but it runs parallel (not really... more on that later) to the rest of the program. Basically allows you to have 2 or more parts of the code execute at almost same time.

code:

process say()
for i:1..10
put "hi"
end for
end say

fork say()

for i:1..10
put i
end for


The result will always differ depending on computer speed, current load, number of processes, etc. If you can the code, you can get an idea of how process really works. The fork is used to call the process but in reality instead of going line by line in both process and main program, the compiler randomly selects which line to execute.

keep that in mind because if you would use locate(row, column) inside your process, that another line might(and probably will) be executed before the next line in the process, so your output will more then likely be deformed.

More about Dynamics
Arguments
Arguments are values that are getting passed to the procedure or a function for it to work with.

Arguments in Procedures
Lets modify our speak() procedure we already made:
code:

procedure speak(word:string)
put word
end speak

speak("tony")


inside the brackets, we declare variables just as we would in our main program, just without the var since we know that those are variables inside. Just as in main program, they need a valid name and :type. If you have more then 1 variable to pass into the procedure, separate them with a comma (,)

down the code, where we call our procedure, I put a string inside the brackets (it could also be a variable) and if you check, the output will be "tony". You can try it out with different words.

Arguments in Functions
Just like with procedures, but I'll give you an example anyway. Here's a modified sum() function that actually finds the sum of what we want.

code:

function sum(num1:int, num2:int) :int
var total:int
total := num1 + num2
result total
end sum

put sum(1, 2)


here the function takes in 2 integers as its arguments, finds their sum, and returns a result based on those numbers.

Arguments in Processes
Just to make things clear - processes can also have arguments.

code:

process say(word:string)
for i:1..10
put word
end for
end say

fork say("tony")

for i:1..10
put i
end for


Procedure Tricks!
Well this wouldn't be a very good tutorial unless I would tell you something more then a standard help file Wink

Self calling procedures
Its a procedure that calls upon itself as a part of the code... What good is that? Lets say it gave me an almost perfect score on J5S3 CCC 2003 - Floor Plan problem Very Happy You know how you should have solved it? with a self-calling procedure I called spread()

code:

procedure spread(x:int, y:int, c:int)

if floor(x+1,y) not= c then
floor(x+1,y) := c
spread(x+1,y,c)
end if

if floor(x-1,y) not= c then
floor(x-1,y) := c
spread(x-1,y,c)
end if

if floor(x,y+1) not= c then
floor(x,y+1) := c
spread(x,y+1,c)
end if

if floor(x,y-1) not= c then
floor(x,y-1) := c
spread(x,y-1,c)
end if

end spread


the problem asked to find areas of rooms from a floor plan input from a file. Well what I've done was that I read the file (left-right, top-bottom) and as soon as I found a symbol representing room space, I filled it with a number(variable c). Then I called upon my spread() procedure. The procedure checked all around itself if there's any more room spaces not marked as a part of the room (in example I forgot to code in to check that its not a wall Confused) and if so, it marks it as the part of this room and calls itself again from the new spot. The result? This quickly marks the whole room with a flag symbol. All I had to do was count those symbols to find the area of the room Very Happy

Conclusion:
Procedures are very useful. If you write specialized procedures with arguments, you can late use it again in your other programs. Such as my text effect's procedures If you save them in a file and include them with your code, you can use those effects in any other program. Don't have to rewrite any of it Wink

Note: I used MS Word to spell check this 1030 word tutorial. If you find that example code doesn't work, please let me know.

Edit: ofcourse the next step would be to write your own classes - collections of functions and procedures which is more rebust then a collection of fucntions/procedures alone. Tutorial available
Sponsor
Sponsor
Sponsor
sponsor
junkpro11




PostPosted: Wed May 12, 2004 8:46 pm   Post subject: (No subject)

one question

i have a procedure. i use procedure(iguess:int) cuz i want to share the value in iguess

but when i tried to manipulate iguess in the procedure, like when i typed
iguess:=iguess+inum

an error comes up saying "left side of assignment is not a varibale and hence cannot be assigned to"
Tony




PostPosted: Wed May 12, 2004 10:11 pm   Post subject: (No subject)

because it is not a variable Laughing it's just a pointer to the value that is being passed on. Such as
code:

procedure something(a:int)
put a
end something

something(1)

the procedure would put "1". In this case the "a" points back to the "1" passed on originally and you can't modify that Wink

what you do is you create a variable inside the function and assign it the desired initial value
code:

procedure something(a:int)
var b:int := a
b:= b+1
put b
end something
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
junkpro11




PostPosted: Wed May 12, 2004 10:59 pm   Post subject: (No subject)

ohh....alrite thanks

i got it fixed now! Smile
zeldamaster1230




PostPosted: Fri May 14, 2004 7:59 am   Post subject: (No subject)

or, if you wanted, you could just make the parameter a variable itself.
code:

procedure smthng (var a : int)
a += 1
end smthng

not to go against what you're doing, Tony.

Cheers!
beard0




PostPosted: Wed Sep 08, 2004 2:01 pm   Post subject: (No subject)

code:
procedure smthng (var a : int)
a += 1
end smthng

would work, but that would make calling smthng(34) impossible. You would need instead to go
code:
var b:=34
smthng(b)
Tony




PostPosted: Thu Sep 09, 2004 12:04 am   Post subject: (No subject)

beard0 wrote:

would work, but that would make calling smthng(34) impossible.


the point of above is to modify the variable, not execute procedure based on a value. This is like a cheap substitute for not making the variable an object. Confused
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
syntax0r




PostPosted: Thu May 05, 2005 6:27 am   Post subject: (No subject)

Does not work http://www.compsci.ca/bbs/viewtopic.php?t=606 Sad

IS there a way, like in C#, to make variables work for only the time that procedure/function is called? So, we can only use that variable upon invoking the procedure/function.

And in turing, do all my variables have to be public?
Sponsor
Sponsor
Sponsor
sponsor
Cervantes




PostPosted: Thu May 05, 2005 2:47 pm   Post subject: (No subject)

If you declare a variable inside a procedure or function or whatever, it's local. Outside, it's global.

example:
Turing:

proc foo
    var bar := 5
end foo
foo
put bar
syntax0r




PostPosted: Thu May 05, 2005 3:01 pm   Post subject: (No subject)

Whoa!

So I gotta be careful. I want all my variables to interact with each other, so I should declare them out of any "proc"

I ran
code:

var bar : string := "WOW 2 var in a .t prog with the exact same name, both showing diff. results?!?!?!?!"


proc foo
    var bar := 5
    put bar
end foo
foo

put bar


And I was suprised "proc" is the same as "procedure"

One more thing. Can I call a procedure within a procedure? For instance:

code:

proc one
put "hello"

    proc two
    put "hello 2"
    end two

end one

one


I ran it, it I got an error saying that I can't. But is there way to pass that?
Tony




PostPosted: Thu May 05, 2005 3:09 pm   Post subject: (No subject)

syntax0r:: links fixed, thx.

as for variables, you might not want to have a lot of global variables because of potential mixups. You could simply pass arguments to the function, use them localy and then return a derived value.
Cervantes




PostPosted: Thu May 05, 2005 3:46 pm   Post subject: (No subject)

You don't really want your variables to interact with each other. This is kind of like thinking about classes. In a class, you'll have lots of variables, but we don't export them. Why? Because we don't want the program to tinker with the object (the instance of the class) in any way other than how the allowed ways specefied by the methods of the class. A nice example wtd told me is thus: you can think of a class as a hand, and your program that uses this class as a hand shake. During the handshake, muscles and other such things in the hand change, as determined by the handshake. However, the handshake cannot change everything about the hand: for example, the handshake cannot stretch one specific muscle to ten times its original length, as that would hurt. Thus, the handshake cannot change the variables of the hand class. However, the handshake can apply a force on the hand, thus moving the hand. The hand would be moved based on a move method of the hand class, not simply by changing the x, y, and z values of the hand. So basically, you don't really want all your variables to be global. Once again, as wtd says, your procedures and functions should be blind to the outside world: ie. we don't import any variables into the procedure/function, save through parameters.
And as to your second question: you can't make a function or procedure within another proc or fcn. These can only be created at the module, class, or monitor level. That means not creating procs within other procs. You can, however, call a procedure/function from within another procedure/function. You can even have your proc/fcn call itself: this is called recursion. Or, you could have proc A call proc B, and proc B calls proc A. This would be mutual recursion.
Tony




PostPosted: Thu May 05, 2005 4:21 pm   Post subject: (No subject)

Cervantes wrote:
And as to your second question: you can't make a function or procedure within another proc or fcn.

Reason being is that a new function will be created every time you call the function up one level.

There is no reason for needed to declear a function within another. If you think you need to, you have a very faulty design. Confused
wtd




PostPosted: Thu May 05, 2005 6:13 pm   Post subject: (No subject)

Tony wrote:
Cervantes wrote:
And as to your second question: you can't make a function or procedure within another proc or fcn.

Reason being is that a new function will be created every time you call the function up one level.

There is no reason for needed to declear a function within another. If you think you need to, you have a very faulty design. Confused


Within languages that support it well, local functions can be quite handy.
Tony




PostPosted: Thu May 05, 2005 8:02 pm   Post subject: (No subject)

wtd wrote:
Within languages that support it well, local functions can be quite handy.

Really? Thinking Could you show me an example? I'm quite interested..
Display posts from previous:   
   Index -> Programming, Turing -> Turing Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 2  [ 20 Posts ]
Goto page 1, 2  Next
Jump to:   


Style:  
Search: