Saturday, November 29, 2008

Learnings of the Week

Submitted by:
Joyce Niko D. Perez
IV- RIZAL

Nov. 24-29, 2008

In this week we continued discussing more of function calls and Sir gave more examples. However, we just had a small time in discussing such matters because our school hosted the Regional Schools Press Conference last Nov. 27-29, 2008.


FUNCTIONS


Using functions we can structure our programs in a more modular way, accessing all the potential that structured programming can offer to us in C++.

A function is a group of statements that is executed when it is called from some point of the program. The following is its format:

type name ( parameter1, parameter2, ...) { statements }

where:

  • type is the data type specifier of the data returned by the function.
  • name is the identifier by which it will be possible to call the function.
  • parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas.
  • statements is the function's body. It is a block of statements surrounded by braces { }.

Here you have the first function example:

// function example
#include
using namespace std;

int addition (int a, int b)
{
int r;
r=a+b;
return (r);
}

int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << class="kw">return 0;
}
The result is 8

In order to examine this code, first of all remember something said at the beginning of this tutorial: a C++ program always begins its execution by the main function. So we will begin there.

We can see how the main function begins by declaring the variable z of type int. Right after that, we see a call to a function called addition. Paying attention we will be able to see the similarity between the structure of the call to the function and the declaration of the function itself some code lines above:

The parameters and arguments have a clear correspondence. Within the main function we called to addition passing two values: 5 and 3, that correspond to the int a and int b parameters declared for function addition.

At the point at which the function is called from within main, the control is lost by main and passed to function addition. The value of both arguments passed in the call (5 and 3) are copied to the local variables int a and int b within the function.

Function addition declares another local variable (int r), and by means of the expression r=a+b, it assigns to r the result of a plus b. Because the actual parameters passed for a and b are 5 and 3 respectively, the result is 8.

The following line of code:

return (r);

finalizes function addition, and returns the control back to the function that called it in the first place (in this case, main). At this moment the program follows it regular course from the same point at which it was interrupted by the call to addition. But additionally, because the return statement in function addition specified a value: the content of variable r (return (r);), which at that moment had a value of 8. This value becomes the value of evaluating the function call.

So being the value returned by a function the value given to the function call itself when it is evaluated, the variable z will be set to the value returned by addition (5, 3), that is 8. To explain it another way, you can imagine that the call to a function (addition (5,3)) is literally replaced by the value it returns (8).

The following line of code in main is:

cout << "The result is " <<>

That, as you may already expect, produces the printing of the result on the screen.

Scope of variables

The scope of variables declared within a function or any other inner block is only their own function or their own block and cannot be used outside of them. For example, in the previous example it would have been impossible to use the variables a, b or r directly in function main since they were variables local to function addition. Also, it would have been impossible to use the variable z directly within function addition, since this was a variable local to the function main.

Therefore, the scope of local variables is limited to the same block level in which they are declared. Nevertheless, we also have the possibility to declare global variables; These are visible from any point of the code, inside and outside all functions. In order to declare global variables you simply have to declare the variable outside any function or block; that means, directly in the body of the program.

And here is another example about functions:

// function example
#include
using namespace std;

int subtraction (int a, int b)
{
int r;
r=a-b;
return (r);
}

int main ()
{
int x=5, y=3, z;
z = subtraction (7,2);
cout << "The first result is " << class="str">'\n';
cout << "The second result is " << class="str">'\n';
cout << "The third result is " << class="str">'\n';
z= 4 + subtraction (x,y);
cout << "The fourth result is " << class="str">'\n';
return 0;
}
The first result is 5
The second result is 5
The third result is 2
The fourth result is 6

In this case we have created a function called subtraction. The only thing that this function does is to subtract both passed parameters and to return the result.

Nevertheless, if we examine function main we will see that we have made several calls to function subtraction. We have used some different calling methods so that you see other ways or moments when a function can be called.

In order to fully understand these examples you must consider once again that a call to a function could be replaced by the value that the function call itself is going to return. For example, the first case (that you should already know because it is the same pattern that we have used in previous examples):

z = subtraction (7,2);
cout << "The first result is " <<>

If we replace the function call by the value it returns (i.e., 5), we would have:

z = 5;
cout << "The first result is " <<>

As well as

cout << "The second result is " <<>

has the same result as the previous call, but in this case we made the call to subtraction directly as an insertion parameter for cout. Simply consider that the result is the same as if we had written:

cout << "The second result is " <<>

since 5 is the value returned by subtraction (7,2).

In the case of:

cout << "The third result is " <<>

The only new thing that we introduced is that the parameters of subtraction are variables instead of constants. That is perfectly valid. In this case the values passed to function subtraction are the values of x and y, that are 5 and 3 respectively, giving 2 as result.

The fourth case is more of the same. Simply note that instead of:

z = 4 + subtraction (x,y);

we could have written:

z = subtraction (x,y) + 4;

with exactly the same result. I have switched places so you can see that the semicolon sign (;) goes at the end of the whole statement. It does not necessarily have to go right after the function call. The explanation might be once again that you imagine that a function can be replaced by its returned value:

z = 4 + 2;
z = 2 + 4;

Functions with no type. The use of void.

If you remember the syntax of a function declaration:

type name ( argument1, argument2 ...) statement

you will see that the declaration begins with a type, that is the type of the function itself (i.e., the type of the datum that will be returned by the function with the return statement). But what if we want to return no value?

Imagine that we want to make a function just to show a message on the screen. We do not need it to return any value. In this case we should use the void type specifier for the function. This is a special specifier that indicates absence of type.

// void function example
#include
using namespace std;

void printmessage ()
{
cout << "I'm a function!";
}

int main ()
{
printmessage ();
return 0;
}
I'm a function!

void can also be used in the function's parameter list to explicitly specify that we want the function to take no actual parameters when it is called. For example, function printmessage could have been declared as:

void printmessage (void)
{
cout << "I'm a function!";
}

Although it is optional to specify void in the parameter list. In C++, a parameter list can simply be left blank if we want a function with no parameters.

What you must always remember is that the format for calling a function includes specifying its name and enclosing its parameters between parentheses. The non-existence of parameters does not exempt us from the obligation to write the parentheses. For that reason the call to printmessage is:

printmessage ();

The parentheses clearly indicate that this is a call to a function and not the name of a variable or some other C++ statement. The following call would have been incorrect:

printmessage;


Arguments passed by value and by reference.

Until now, in all the functions we have seen, the arguments passed to the functions have been passed by value. This means that when calling a function with parameters, what we have passed to the function were copies of their values but never the variables themselves. For example, suppose that we called our first function addition using the following code:

int x=5, y=3, z;
z = addition ( x , y );

What we did in this case was to call to function addition passing the values of x and y, i.e. 5 and 3 respectively, but not the variables x and y themselves.

This way, when the function addition is called, the value of its local variables a and b become 5 and 3 respectively, but any modification to either a or b within the function addition will not have any effect in the values of x and y outside it, because variables x and y were not themselves passed to the function, but only copies of their values at the moment the function was called.

But there might be some cases where you need to manipulate from inside a function the value of an external variable. For that purpose we can use arguments passed by reference, as in the function duplicate of the following example:

// passing parameters by reference
#include
using namespace std;

void duplicate (int& a, int& b, int& c)
{
a*=2;
b*=2;
c*=2;
}

int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << class="str">", y=" << class="str">", z=" << class="kw">return 0;
}
x=2, y=6, z=14

The first thing that should call your attention is that in the declaration of duplicate the type of each parameter was followed by an ampersand sign (&). This ampersand is what specifies that their corresponding arguments are to be passed by reference instead of by value.

When a variable is passed by reference we are not passing a copy of its value, but we are somehow passing the variable itself to the function and any modification that we do to the local variables will have an effect in their counterpart variables passed as arguments in the call to the function.

To explain it in another way, we associate a, b and c with the arguments passed on the function call (x, y and z) and any change that we do on a within the function will affect the value of x outside it. Any change that we do on b will affect y, and the same with c and z.

That is why our program's output, that shows the values stored in x, y and z after the call to duplicate, shows the values of all the three variables of main doubled.

If when declaring the following function:

void duplicate (int& a, int& b, int& c)

we had declared it this way:

void duplicate (int a, int b, int c)

i.e., without the ampersand signs (&), we would have not passed the variables by reference, but a copy of their values instead, and therefore, the output on screen of our program would have been the values of x, y and z without having been modified.

Passing by reference is also an effective way to allow a function to return more than one value. For example, here is a function that returns the previous and next numbers of the first parameter passed.

// more than one returning value
#include
using namespace std;

void prevnext (int x, int& prev, int& next)
{
prev = x-1;
next = x+1;
}

int main ()
{
int x=100, y, z;
prevnext (x, y, z);
cout << "Previous=" << class="str">", Next=" << class="kw">return 0;
}
Previous=99, Next=101  

Default values in parameters.

When declaring a function we can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function. To do that, we simply have to use the assignment operator and a value for the arguments in the function declaration. If a value for that parameter is not passed when the function is called, the default value is used, but if a value is specified this default value is ignored and the passed value is used instead. For example:
// default values in functions
#include
using namespace std;

int divide (int a, int b=2)
{
int r;
r=a/b;
return (r);
}

int main ()
{
cout << class="kw">return 0;
}
6
5

As we can see in the body of the program there are two calls to function divide. In the first one:

divide (12)

we have only specified one argument, but the function divide allows up to two. So the function divide has assumed that the second parameter is 2 since that is what we have specified to happen if this parameter was not passed (notice the function declaration, which finishes with int b=2, not just int b). Therefore the result of this function call is 6 (12/2).

In the second call:

divide (20,4)

there are two parameters, so the default value for b (int b=2) is ignored and b takes the value passed as argument, that is 4, making the result returned equal to 5 (20/4).

Overloaded functions.

In C++ two different functions can have the same name if their parameter types or number are different. That means that you can give the same name to more than one function if they have either a different number of parameters or different types in their parameters. For example:
// overloaded function
#include
using namespace std;

int operate (int a, int b)
{
return (a*b);
}

float operate (float a, float b)
{
return (a/b);
}

int main ()
{
int x=5,y=2;
float n=5.0,m=2.0;
cout << class="str">"\n";
cout << class="str">"\n";
return 0;
}
10
2.5

In this case we have defined two functions with the same name, operate, but one of them accepts two parameters of type int and the other one accepts them of type float. The compiler knows which one to call in each case by examining the types passed as arguments when the function is called. If it is called with two ints as its arguments it calls to the function that has two int parameters in its prototype and if it is called with two floats it will call to the one which has two float parameters in its prototype.

In the first call to operate the two arguments passed are of type int, therefore, the function with the first prototype is called; This function returns the result of multiplying both parameters. While the second call passes two arguments of type float, so the function with the second prototype is called. This one has a different behavior: it divides one parameter by the other. So the behavior of a call to operate depends on the type of the arguments passed because the function has been overloaded.

Notice that a function cannot be overloaded only by its return type. At least one of its parameters must have a different type.

inline functions.

The inline specifier indicates the compiler that inline substitution is preferred to the usual function call mechanism for a specific function. This does not change the behavior of a function itself, but is used to suggest to the compiler that the code generated by the function body is inserted at each point the function is called, instead of being inserted only once and perform a regular call to it, which generally involves some additional overhead in running time.

The format for its declaration is:

inline type name ( arguments ... ) { instructions ... }

and the call is just like the call to any other function. You do not have to include the inline keyword when calling the function, only in its declaration.

Most compilers already optimize code to generate inline functions when it is more convenient. This specifier only indicates the compiler that inline is preferred for this function.

Recursivity.

Recursivity is the property that functions have to be called by themselves. It is useful for many tasks, like sorting or calculate the factorial of numbers. For example, to obtain the factorial of a number (n!) the mathematical formula would be:
n! = n * (n-1) * (n-2) * (n-3) ... * 1

more concretely, 5! (factorial of 5) would be:

5! = 5 * 4 * 3 * 2 * 1 = 120

and a recursive function to calculate this in C++ could be:

// factorial calculator
#include
using namespace std;

long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return (1);
}

int main ()
{
long number;
cout << "Please type a number: ";
cin >> number;
cout << class="str">"! = " << class="kw">return 0;
}
Please type a number: 9
9! = 362880

Notice how in function factorial we included a call to itself, but only if the argument passed was greater than 1, since otherwise the function would perform an infinite recursive loop in which once it arrived to 0 it would continue multiplying by all the negative numbers (probably provoking a stack overflow error on runtime).

This function has a limitation because of the data type we used in its design (long) for more simplicity. The results given will not be valid for values much greater than 10! or 15!, depending on the system you compile it.

Declaring functions.

Until now, we have defined all of the functions before the first appearance of calls to them in the source code. These calls were generally in function main which we have always left at the end of the source code. If you try to repeat some of the examples of functions described so far, but placing the function main before any of the other functions that were called from within it, you will most likely obtain compiling errors. The reason is that to be able to call a function it must have been declared in some earlier point of the code, like we have done in all our examples.

But there is an alternative way to avoid writing the whole code of a function before it can be used in main or in some other function. This can be achieved by declaring just a prototype of the function before it is used, instead of the entire definition. This declaration is shorter than the entire definition, but significant enough for the compiler to determine its return type and the types of its parameters.

Its form is:

type name ( argument_type1, argument_type2, ...);

It is identical to a function definition, except that it does not include the body of the function itself (i.e., the function statements that in normal definitions are enclosed in braces { }) and instead of that we end the prototype declaration with a mandatory semicolon (;).

The parameter enumeration does not need to include the identifiers, but only the type specifiers. The inclusion of a name for each parameter as in the function definition is optional in the prototype declaration. For example, we can declare a function called protofunction with two int parameters with any of the following declarations:

int protofunction (int first, int second);
int protofunction (int, int);

Anyway, including a name for each variable makes the prototype more legible.

// declaring functions prototypes
#include
using namespace std;

void odd (int a);
void even (int a);

int main ()
{
int i;
do {
cout << "Type a number (0 to exit): ";
cin >> i;
odd (i);
} while (i!=0);
return 0;
}

void odd (int a)
{
if ((a%2)!=0) cout << "Number is odd.\n";
else even (a);
}

void even (int a)
{
if ((a%2)==0) cout << "Number is even.\n";
else odd (a);
}
Type a number (0 to exit): 9
Number is odd.
Type a number (0 to exit): 6
Number is even.
Type a number (0 to exit): 1030
Number is even.
Type a number (0 to exit): 0
Number is even.

This example is indeed not an example of efficiency. I am sure that at this point you can already make a program with the same result, but using only half of the code lines that have been used in this example. Anyway this example illustrates how prototyping works. Moreover, in this concrete example the prototyping of at least one of the two functions is necessary in order to compile the code without errors.

The first things that we see are the declaration of functions odd and even:

void odd (int a);
void even (int a);

This allows these functions to be used before they are defined, for example, in main, which now is located where some people find it to be a more logical place for the start of a program: the beginning of the source code.

Anyway, the reason why this program needs at least one of the functions to be declared before it is defined is because in odd there is a call to even and in even there is a call to odd. If none of the two functions had been previously declared, a compilation error would happen, since either odd would not not be visible from even (because it has still not been declared), or even would not be visible from odd (for the same reason).

Having the prototype of all functions together in the same place within the source code is found practical by some programmers, and this can be easily achieved by declaring all functions prototypes at the beginning of a program.

Learnings of the Week [November 24-28, 2008]

In this week, we continued discussing about functions. But Sir Balbuena met us only once because our school held the Regional Press Conference.

Pass by Value

The actual parameter is fully evaluated and the resulting value is copied into a location being used to hold the formal parameter's value during method/function execution. That location is typically a chunk of memory on the runtime stack for the application (which is how Java handles it), but other languages could choose parameter storage differently.


Pass by Reference

The formal parameter merely acts as an alias for the actual parameter. Anytime the method/function uses the formal parameter (for reading or writing), it is actually using the actual parameter.

Call by Value

In the method call by value, the values of the actual parameters are passed to the formal parameters. Changes that happen to the values of the formal parameters inside the function will not affect the values of the actual parameters.

ACTUAL AND FORMAL PARAMETERS

Actual Parameters are the variables found in the function call whose values will be passed to the formal parameters of the called function.

Formal Parameters are the variables found in the function header that will receive from the actual parameters.

Scope of variables

The scope of variables declared within a function or any other inner block is only their own function or their own block and cannot be used outside of them.



Posted by:
RAE ANGELINE S. PALEN
IV - Rizal

Learnigs of the week- November 24-28,2008

we've only met once so during this meeting, Sir Balbuena discussed about...

Pass by Value


The actual parameter is fully evaluated and the resulting value is copied into a location being used to hold the formal parameter's value during method/function execution. That location is typically a chunk of memory on the runtime stack for the application (which is how Java handles it), but other languages could choose parameter storage differently.


Pass by Reference

The formal parameter merely acts as an alias for the actual parameter. Anytime the method/function uses the formal parameter (for reading or writing), it is actually using the actual parameter.

Call by Value

In the method call by value, the values of the actual parameters are passed to the formal parameters. Changes that happen to the values of the formal parameters inside the function will not affect the values of the actual parameters.

ACTUAL AND FORMAL PARAMETERS

Actual Parameters are the variables found in the function call whose values will be passed to the formal parameters of the called function.

Formal Parameters are the variables found in the function header that will receive from the actual parameters.

Scope of variables

The scope of variables declared within a function or any other inner block is only their own function or their own block and cannot be used outside of them.


by: Hanna Deborrah T. Ongking IV- Rizal

Sunday, November 23, 2008

Learnings of the Week [November 17-21, 2008]

In this week, we tackled about the. . .


FUNCTIONS AND STRUCTURED PROGRAMMING

A C program is composed of at least one function definition, that is the main() function. Execution of the program begins with main() and also ends with the main() function. However, a c program can also be composed of other functions aside from the main().

The C program presented in previous slide is composed of 3 functions: the main function, function greet1, and function greet2. Therefore, we can say that we can create a program that is composed of other function aside from the main function. Note that the main() function should always be present in every C program.

FUNCTIONS DEFINED

Functions are the building blocks of C in which all program activity occurs. A function is also called a subprogram or subroutine. It is a part of a C program that performs a task, operation or computation then may return to the calling part of the program. Other functions aside from the main() can only be executed by the programming through a “function call’. Note that the function call is a c statement that is used to call a function to execute C statements found inside the function body.

The general form of the function is:

function_type function_name (parameters list)

{

body of the function;

}

function_type

- specifies the type of value that the function will return

function_name

- is any valid identifier name which will name the function

Parameter list

- is a comma separated list of variables that receive the values when the function is called

Body of the function

- is composed of valid c statements that the function will execute

TYPES OF FUNCTIONS

Void Functions - which does not return any value when invoked.

Function that returns a value once invoked.

ACTUAL AND FORMAL PARAMETERS

Actual Parameters are the variables found in the function call whose values will be passed to the formal parameters of the called function.

Formal Parameters are the variables found in the function header that will receive from the actual parameters.

CALL BY VALUE

In the method call by value, the values of the actual parameters are passed to the formal parameters. Changes that happen to the values of the formal parameters inside the function will not affect the values of the actual parameters.

PASS BY VALUE OR CALL BY REFERENCE

The actual parameters also pass their value to the formal parameters. But the changes that happen to the values of the formal parameters inside the function will affect the values of the actual parameters. This is because the actual address of the variables is passed using the address of operator (&) together with the pointer operator (*).

<#include

sqrt(x)

fabs(x)

- calculates the absolute value of a number

ceil(x)

- ceil (11.25) = 12

floor(x)

- floor (11.25) = 11

sin(x)

cos(x)

tan(x)

pow(x)





Posted by:

RAE ANGELINE S. PALEN
IV - Rizal


Friday, November 21, 2008

Learnings of the Week

Submitted by:

Joyce Niko D. Perez
IV-RIZAL

November 17-21, 2008

In this week, we learned about

STRUCTURED PROGRAMMING USING FUNCTIONS


• A function is a self-contained block of code with a specific purpose.

• A function has a name that both identifies it and is used to call it for execution in a program.

• Functions which perform different actions should generally have different names.


Why Do You Need Functions?

• Functions can be executed as many times as necessary from different points in a program.

• Without the ability to package a block of code into a function, programs would end up being
much larger, since you would typically need to replicate the same code at various points in
your program.

• But the real reason that you need functions is to modularize your program into easily
manageable chunks.

Functions

• Functions allow a program to be segmented so that it can be written piecemeal, and each piece tested independently before bringing it together with the other pieces.

• It also allows the work to be divided among members of a programming team, with each team
member taking responsibility for a tightly specified piece of the program, with a well defined
functional interface to the rest of the code.

• Real world large scale programming projects are developed using this approach

• The name of a function is governed by the same rules as those for a variable.

• You pass information to a function using its arguments which are specified when you invoke
or call it.

• The arguments need to correspond with parameters appearing in the definition of the function.

• The arguments replace the parameters used in the function definition when the function is executed.

• The code in the function then executes as though it was written using your argument values.


Structure of Functions using Function Definition

• A Function Definition is the “self-contained block of code with a specific purpose”.

• A functions definition has to two distinct parts: a function header, followed by the body of the function.

• Functions Header which identifies the function – Tells the compiler what the function is and its return
type

• Function Body between curly braces containing the executable code for the function
– the actual executable part of the function.


The General Form of a Function Header

• Function header consists of three parts:
– the type of the return value
– the name of the function,
– the parameters of the function enclosed between
parentheses.

• The general form of a function header can be written as
follows:
return_type
FunctionName(parameter_list)

• No semicolon is required at the end of the function header.

Function Prototypes

• Before you can use a function in a program, you must declare the function using a statement called a function prototype.

• Function prototype informs the compiler of the framework for that function.

• A prototype of a function provides the basic information that the compiler needs to check that a function is used correctly.

• It specifies:
– the parameters to be passed to the function,
– the function name, and
– the type of the return value;

• it contains essentially the same information as appears in the function header, with the addition
of a semicolon.

• a semicolon is required at the end of a function prototype.

• The number of parameters and their types must be the same in the function prototype as they are in the function header in the definition of the function.

• The prototypes for the functions used in a program must appear before the statements calling the functions.

Naming of Parameters in function header and prototype

• A parameter name in the function prototype should provide an understanding about why it is
used.

• You can specified different names for the parameters in the function prototype to those
used in the function header when you defined the function.

• Most often, the same names are used in the prototype and in the function header in the
definition of the function, but this doesn't have to be so.

Header Files for Function

Prototypes

• Header files is a C++ files that has a .h extension, appear between <> in a #include statement.

• The header files which we've been including for standard library functions include the prototypes of the functions provided by the library.

• If your code uses a lot of functions, it is a good idea to place all function prototypes in a header
file.

• In the header file, the function prototypes are stored along with a brief description of the
purpose of the function.

What is returned by a Function

• A function communicates back with the rest of the program using its return statement

• The return_type can be any legal type.

• The return value is returned to the calling function when the function is executed, so when
the function is called

• The return type will have the same type as in the declaration of the function.

• A copy of the value being returned is made automatically, it is available to the return point in
the program.


The return Statement

• The return statement returns a value to the calling program at the point where the function

• The general form of the return statement is as follows, return expression;

• expression must evaluate to a value of the type specified in the function header for the return value.

• The expression can be any expression you want, as long as you end up with a value of the required type.

• If the type of return value has been specified as void, there must be no expression appearing in the return statement. It must be written simply as: return


Keyword void used in functions

• If the function does not return a value, the return type is specified by the keyword void.

• The keyword void is also used to indicate that a function has no parameters and doesn't return a value void MyFunction(void)

• An empty parameter list also indicates that a function takes no arguments, so you could omit the keyword void between the parentheses as follows: void MyFunction()

• A function with a return type specified as void should not be used in an expression in the calling program.

Function Body

• Functions should begin with { and end with }.

• All the variables declared within the body of a function, as well as the parameters, are local to the function.

• The scope of variables declared within a function is determined in the same way that we have already discussed.

• A variable is created at the point at which it is defined and ceases to exist at the end of the block containing it.

• Be careful about masking global variables with local variables of the same name.


Function Arguments

• Parameters are used in the function prototype but functions receive input from the rest of the
program using arguments.

• Arguments can be any expression, or variables as long as a value of the correct type is
ultimately produced.

• The arguments substitute the parameters that were used in the definition of the function.


Calling a Function

• When you call a function, you are telling the compiler branch off and execute the piece of code
that defines the function.

• The computation is performed using these values, then a copy of the result, will be returned to the calling function which stores it in the appropriate argument.

• You can think of the function as having this value in the statement or expression in which it appears

• To call a function, use the function name followed by arguments enclosed in parenthesis.


Passing Arguments to a Function

• The arguments specified when a function is called should usually correspond in type and
sequence to the parameters appearing in the definition of the function.

• If the type of an argument specified in a function call doesn't correspond with the type
of parameter in the function definition, then (where possible) it will be converted to the
required type.

Methods of transferring data to a function

• Pass-by-value method of transferring data to a function

– With this mechanism, the variables or constants that you specify as arguments are not passed to a function at all. Instead, copies of the arguments are created and these copies are used as the values to be transferred.

• Pass-by-reference method of transferring date to a function.

– The method used is not pass-by-value where an argument is copied before being passed, but pass-by reference where the parameter acts as an alias for the argument passed.


Pass-by-value method

• Each time you call a function, the compiler arranges for copies of the arguments that you
specify to be stored in a temporary location in memory.

• During execution of the functions, all references to the function parameters will be mapped to these temporary copies of the arguments.

• Clearly, the pass-by-value mechanism provides you with a high degree of protection from having your caller arguments mauled by a rogue function, but it is conceivable that we might actually want to arrange to modify caller arguments.


Passing Arrays to functions

• You can also pass an array to a function, but in this case the array is not copied, even though a pass-by value method of passing arguments still applies.

• The array name is converted to a pointer (is an address of a variable), and a copy of the pointer to the beginning of the array is passed to the function.

• This is quite advantageous, as copying large arrays could be very time and memory consuming.

• To pass an array to a function, just specify the name of the array in the argument list.

• In Multidimensional Arrays follow the same procedure


Other methods of communicating with a function

• Specifying a parameter to a function as a reference changes the method of passing data
for that parameter.

• This eliminates any copying and allows the function to access the caller argument directly.

• It also means that the de-referencing, which is required when passing and using a pointer to a
value, is also unnecessary.

• We will revisit this a method after we introduce pointers and reference

Array Functions

Arrays are a big part of the Perl language and Perl has a lot of functions to help you work with them. Some of the actions arrays perform include deleting elements, checking for the existence of an element, reversing all of the the elements in an array, and sorting the elements. Table 5.2 lists the functions you can use with arrays.

Table 5.2 Array Functions

FunctionDescription
defined(VARIABLE) Returns true if VARIABLE has a real value and if the variable has not yet been assigned a value. This is not limited to arrays; any data type can be checked. Also see the exists function for information about associative array keys.
delete(KEY) Removes the key-value pair from the given associative array. If you delete a value from the %ENV array, the environment of the current process is changed, not that of the parent.
each(ASSOC_ARRAY) Returns a two-element list that contains a key and value pair from the given associative array. The function is mainly used so you can iterate over the associate array elements. A null list is returned when the last element has been read.
exists(KEY) Returns true if the KEY is part of the specified associative array. For instance, exists($array{"Orange"}) returns true if the %array associative array has a key with the value of "Orange."
join(STRING, ARRAY) Returns a string that consists of all of the elements of ARRAY joined together by STRING. For instance, join(">>", ("AA", "BB", "cc")) returns "AA>>BB>>cc".
keys(ASSOC_ARRAY) Returns a list that holds all of the keys in a given associative array. The list is not in any particular order.
map(EXPRESSION, ARRAY) Evaluates EXPRESSION for every element of ARRAY. The special variable $ is assigned each element of ARRAY immediately before EXPRESSION is evaluated.
pack(STRING, ARRAY) Creates a binary structure, using STRING as a guide, of the elements of ARRAY. You can look in Chapter 8 "References," for more information.
pop(ARRAY) Returns the last value of an array. It also reduces the size of the array by one.
push(ARRAY1, ARRAY2) Appends the contents of ARRAY2 to ARRAY1. This increases the size of ARRAY1 as needed.
reverse(ARRAY) Reverses the elements of a given array when used in an array context. When used in a scalar context, the array is converted to a string, and the string is reversed.
scalar(ARRAY) Evaluates the array in a scalar context and returns the number of elements in the array.
shift(ARRAY) Returns the first value of an array. It also reduces the size of the array by one.
sort(ARRAY) Returns a list containing the elements of ARRAY in sorted order. See Chapter 8 "References," for more information.
splice(ARRAY1, OFFSET, Replaces elements of ARRAY1 with elements
LENGTH, ARRAY2) in ARRAY2. It returns a list holding any elements that were removed. Remember that the $[ variable may change the base array subscript when determining the OFFSET value.
split(PATTERN, STRING, LIMIT) Breaks up a string based on some delimiter. In an array context, it returns a list of the things that were found. In a scalar context, it returns the number of things found.
undef(VARIABLE) Always returns the undefined value. In addition, it undefines VARIABLE, which must be a scalar, an entire array, or a subroutine name.
unpack(STRING, ARRAY) Does the opposite of pack().
unshift(ARRAY1, ARRAY2) Adds the elements of ARRAY2 to the front of ARRAY1. Note that the added elements retain their original order. The size of the new ARRAY1 is returned.
values(ASSOC_ARRAY) Returns a list that holds all of the values in a given associative array. The list is not in any particular order.

Learnigs of the week- November 17-21,2008


STRUCTURED PROGRAMMING USING FUNCTIONS

• A function is a self-contained block of code with a specific purpose.

• A function has a name that both identifies it and is used to call it for execution in a program.

• Functions which perform different actions should generally have different names.


Why Do You Need Functions?

• Functions can be executed as many times as necessary from different points in a program.

• Without the ability to package a block of code into a function, programs would end up being
much larger, since you would typically need to replicate the same code at various points in
your program.

• But the real reason that you need functions is to modularize your program into easily
manageable chunks.

Functions


• Functions allow a program to be segmented so that it can be written piecemeal, and each piece tested independently before bringing it together with the other pieces.

• It also allows the work to be divided among members of a programming team, with each team
member taking responsibility for a tightly specified piece of the program, with a well defined
functional interface to the rest of the code.

• Real world large scale programming projects are developed using this approach

• The name of a function is governed by the same rules as those for a variable.

• You pass information to a function using its arguments which are specified when you invoke
or call it.

• The arguments need to correspond with parameters appearing in the definition of the function.

• The arguments replace the parameters used in the function definition when the function is executed.

• The code in the function then executes as though it was written using your argument values.


Structure of Functions using Function Definition

• A Function Definition is the “self-contained block of code with a specific purpose”.

• A functions definition has to two distinct parts: a function header, followed by the body of the function.

• Functions Header which identifies the function – Tells the compiler what the function is and its return
type

• Function Body between curly braces containing the executable code for the function
– the actual executable part of the function.


The General Form of a Function Header

• Function header consists of three parts:
– the type of the return value
– the name of the function,
– the parameters of the function enclosed between
parentheses.

• The general form of a function header can be written as
follows:
return_type
FunctionName(parameter_list)

• No semicolon is required at the end of the function header.

Function Prototypes


• Before you can use a function in a program, you must declare the function using a statement called a function prototype.

• Function prototype informs the compiler of the framework for that function.

• A prototype of a function provides the basic information that the compiler needs to check that a function is used correctly.

• It specifies:
– the parameters to be passed to the function,
– the function name, and
– the type of the return value;

• it contains essentially the same information as appears in the function header, with the addition
of a semicolon.

• a semicolon is required at the end of a function prototype.

• The number of parameters and their types must be the same in the function prototype as they are in the function header in the definition of the function.

• The prototypes for the functions used in a program must appear before the statements calling the functions.

Naming of Parameters in function header and prototype

• A parameter name in the function prototype should provide an understanding about why it is
used.

• You can specified different names for the parameters in the function prototype to those
used in the function header when you defined the function.

• Most often, the same names are used in the prototype and in the function header in the
definition of the function, but this doesn't have to be so.

Header Files for Function


Prototypes

• Header files is a C++ files that has a .h extension, appear between <> in a #include statement.

• The header files which we've been including for standard library functions include the prototypes of the functions provided by the library.

• If your code uses a lot of functions, it is a good idea to place all function prototypes in a header
file.

• In the header file, the function prototypes are stored along with a brief description of the
purpose of the function.

What is returned by a Function


• A function communicates back with the rest of the program using its return statement

• The return_type can be any legal type.

• The return value is returned to the calling function when the function is executed, so when
the function is called

• The return type will have the same type as in the declaration of the function.

• A copy of the value being returned is made automatically, it is available to the return point in
the program.


The return Statement


• The return statement returns a value to the calling program at the point where the function

• The general form of the return statement is as follows, return expression;

• expression must evaluate to a value of the type specified in the function header for the return value.

• The expression can be any expression you want, as long as you end up with a value of the required type.

• If the type of return value has been specified as void, there must be no expression appearing in the return statement. It must be written simply as: return


Keyword void used in functions


• If the function does not return a value, the return type is specified by the keyword void.

• The keyword void is also used to indicate that a function has no parameters and doesn't return a value void MyFunction(void)

• An empty parameter list also indicates that a function takes no arguments, so you could omit the keyword void between the parentheses as follows: void MyFunction()

• A function with a return type specified as void should not be used in an expression in the calling program.

Function Body


• Functions should begin with { and end with }.

• All the variables declared within the body of a function, as well as the parameters, are local to the function.

• The scope of variables declared within a function is determined in the same way that we have already discussed.

• A variable is created at the point at which it is defined and ceases to exist at the end of the block containing it.

• Be careful about masking global variables with local variables of the same name.


Function Arguments


• Parameters are used in the function prototype but functions receive input from the rest of the
program using arguments.

• Arguments can be any expression, or variables as long as a value of the correct type is
ultimately produced.

• The arguments substitute the parameters that were used in the definition of the function.


Calling a Function


• When you call a function, you are telling the compiler branch off and execute the piece of code
that defines the function.

• The computation is performed using these values, then a copy of the result, will be returned to the calling function which stores it in the appropriate argument.

• You can think of the function as having this value in the statement or expression in which it appears

• To call a function, use the function name followed by arguments enclosed in parenthesis.


Passing Arguments to a Function


• The arguments specified when a function is called should usually correspond in type and
sequence to the parameters appearing in the definition of the function.

• If the type of an argument specified in a function call doesn't correspond with the type
of parameter in the function definition, then (where possible) it will be converted to the
required type.

Methods of transferring data to a function

• Pass-by-value method of transferring data to a function

– With this mechanism, the variables or constants that you specify as arguments are not passed to a function at all. Instead, copies of the arguments are created and these copies are used as the values to be transferred.

• Pass-by-reference method of transferring date to a function.

– The method used is not pass-by-value where an argument is copied before being passed, but pass-by reference where the parameter acts as an alias for the argument passed.


Pass-by-value method

• Each time you call a function, the compiler arranges for copies of the arguments that you
specify to be stored in a temporary location in memory.

• During execution of the functions, all references to the function parameters will be mapped to these temporary copies of the arguments.

• Clearly, the pass-by-value mechanism provides you with a high degree of protection from having your caller arguments mauled by a rogue function, but it is conceivable that we might actually want to arrange to modify caller arguments.


Passing Arrays to functions

• You can also pass an array to a function, but in this case the array is not copied, even though a pass-by value method of passing arguments still applies.

• The array name is converted to a pointer (is an address of a variable), and a copy of the pointer to the beginning of the array is passed to the function.

• This is quite advantageous, as copying large arrays could be very time and memory consuming.

• To pass an array to a function, just specify the name of the array in the argument list.

• In Multidimensional Arrays follow the same procedure


Other methods of communicating with a function

• Specifying a parameter to a function as a reference changes the method of passing data
for that parameter.

• This eliminates any copying and allows the function to access the caller argument directly.

• It also means that the de-referencing, which is required when passing and using a pointer to a
value, is also unnecessary.

• We will revisit this a method after we introduce pointers and reference



by: Hanna Deborrah T. Ongking IV- Rizal

Friday, November 14, 2008

Learnings of the Week

Submitted by:
Joyce Niko D. Perez
IV- RIZAL

Nov. 10-14, 2008

This week we had activities and discussions on the selective switch statements and many other iterative statements.

The selective structure: switch.

The syntax of the switch statement is a bit peculiar. Its objective is to check several possible constant values for an expression. Something similar to what we did at the beginning of this section with the concatenation of several if and else if instructions. Its form is the following:
switch (expression)
{
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break;
.
.
.
default:
default group of statements
}

It works in the following way: switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes group of statements 1 until it finds the break statement. When it finds this break statement the program jumps to the end of the switch selective structure.

If expression was not equal to constant1 it will be checked against constant2. If it is equal to this, it will execute group of statements 2 until a break keyword is found, and then will jump to the end of the switch selective structure.

Finally, if the value of expression did not match any of the previously specified constants (you can include as many case labels as values you want to check), the program will execute the statements included after the default: label, if it exists (since it is optional).

Both of the following code fragments have the same behavior:

switch exampleif-else equivalent
switch (x) {
case 1:
cout << "x is 1";
break;
case 2:
cout << "x is 2";
break;
default:
cout << "value of x unknown";
}
if (x == 1) {
cout << "x is 1";
}
else if (x == 2) {
cout << "x is 2";
}
else {
cout << "value of x unknown";
}

The switch statement is a bit peculiar within the C++ language because it uses labels instead of blocks. This forces us to put break statements after the group of statements that we want to be executed for a specific condition. Otherwise the remainder statements -including those corresponding to other labels- will also be executed until the end of the switch selective block or a break statement is reached.

For example, if we did not include a break statement after the first group for case one, the program will not automatically jump to the end of the switch selective block and it would continue executing the rest of statements until it reaches either a break instruction or the end of the switch selective block. This makes unnecessary to include braces { } surrounding the statements for each of the cases, and it can also be useful to execute the same block of instructions for different possible values for the expression being evaluated. For example:

switch (x) {
case 1:
case 2:
case 3:
cout << "x is 1, 2 or 3";
break;
default:
cout << "x is not 1, 2 nor 3";
}

Notice that switch can only be used to compare an expression against constants. Therefore we cannot put variables as labels (for example case n: where n is a variable) or ranges (case (1..3):) because they are not valid C++ constants.

If you need to check ranges or values that are not constants, use a concatenation of if and else if statements.

Learnings of the Week [November 10-14, 2008]

In this week, our lesson is about the Switch Statement.

The Switch Statement

A switch statement is a selection statement that lets you transfer control to different statements within the switch body depending on the value of the switch expression. The switch expression must evaluate to an integral or enumeration value. The body of the switch statement contains case clauses that consist of a case label, an option default label, a case expression, and a list of statements.

A switch statement has the form:

>>-switch--(--expression--)--switch_body-----------------------------------------><

The switch body is enclosed in braces and can contain definitions, declarations, case clauses, and a default clause.



Posted by:
RAE ANGELINE S. PALEN
IV - Rizal