chapter_9

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Map of the course

1. History (of the Programming language C++)


2. Literature
3. A first example
4. Some remarks on the compilation and binding of programs
5. The programming environment Dev-C++
6. Expressions in C++
7. Formatted input and output
8. Control structures
9. Functions
10. Arrays
11. Using files
1
9. Functions
• Splitting a complex task into several simpler tasks
• Re-use of partial problem solutions, for example, an equation solver
• Test of individual modules
• Distribution of tasks to a team of developers

9.1 Structure of a function

List of parameters
(optional)

Type Function
(mandatory)

Return value (optional)


equal to the type of the function

2
Its just the same as in math …

Function Call 𝑦 = 𝑓(𝑥)

Result Argument(s)
Name

What does the function do?


Function Definition 𝑓 𝑥 = 𝑥2 + 7 𝑥 − 3

3
Function Definition
T y p e _ o f_ r e tu r n _ v a lu e F u n c t io n _ n a m e ( p a r a m e te r lis t )
{ // o p e n b lo c k ( b o d y ) : c r e a te s a lo c a l s c o p e fo r th e fu n c tio n

// im p le m e n ta tio n o f th e th e fu n c tio n

r e tu r n r e tu r n _ v a lu e ; // r e tu r n to c a llin g fu n c tio n
// th e ty p e o f th e r e tu r n v a lu e is e q u a l to th e ty p e o f th e
// fu n c tio n
} // c lo s e b lo c k

Example: Compute the Euclidean distance of two points with coordinates (x1,y1)
and (x2,y2).
double length(double x1, double y1, double x2, double y2)
{
double a;
a = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
return a;
}
Example: 6_d
4
Return value
In general, a function returns a value via the return-statement:

return return_value;
return_value can be:
 a variable
double length(double x1, double y1, double x2, double y2)
{
double a;
a = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
return a;
}

 an arithmetic expression
double length(double x1, double y1, double x2, double y2)
{
return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}

 a logical expression
6
A return value

can (yet must not necessarily)


be used in the calling function, for example,

1) on the right-hand side of an assignment statement


double s;
double u1, v1, u2, v2;
.....
s = length(u1, v1, u2, v2);
printf(“Length = %f\n“, s);

2) or as a parameter of another function

double u1, v1, u2, v2;


.....
printf(“Length = %f\n“, length(u1, v1, u2, v2));

7
Return value void

void is a special return type, where the return-statement does not send
a value back to the calling function.

Example:

void length(double x1, double y1, double x2, double y2)


{
double a;
a = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
printf(“Length = %f\n“, a);
return;
}

8
Formal and actual parameters
Formal parameters are those given in the declaration (prototype) and definition
(implementation) of the function.
e.g. function length: x1, y1, x2, y2

Actual parameters are those used in the calling of the function.


e.g. function length: u1, v1, u2, v2

The following rules should be used:

• The sequence of parameters must be the same in the protoype and in the
calling of the function

• The datatypes of individual parameters must be the same or must be


transferable („cast“) into each other

9
Function prototypes
Variables: have to be declared to the compiler
Declaration

Type_ of _ Variable Name_of_Variable;


Definition
Name_of_Variable = some_value;

Functions: have to be declared to the compiler


Declaration of a function is called a function prototype

Type_of_return_value Function_name(parameterlist);
The semicolon at the end of the declaration is mandatory!
Definition
The body of the function that was declared (i.e. the implementation)

10
Code Modularization: the include concept
Our Code
External
Source File Header File
# include <A.h>
(Implementation) (Prototypes) # include <B.h>
use # include <C.h>
A.c A.h
use
B.c B.h

Compiled Content
(Libraries) use

C.lib B.h
Example: 6e
12
The include concept
• Using the #include <name> command the preprocessor inserts the file
<name> before compilation into the source file
Example:
# in c lu d e < s t d io .h >
...
p r in tf( “ % d “ , i) ;
...

• If the function protype is missing, the compiler generates an error message:


undeclared identifier ....

13
Important header files

Header file Contents

stdio.h Input and output

math.h Mathematical functions:


e.g.: sin, cos, fabs, sqrt
string.h Functions to manipulate character strings

time.h Date and time

limits.h Limit values of different data types

stdlib.h or cstdlib Standard functions like, for example, exit

14
The Call Stack

function calls Recursive function calls


calls myLastFunction() myRecursiveFunction()
returns

calls returns
mySecondFunction() myRecursiveFunction()
calls returns
myFirstFunction() myRecursiveFunction()
calls returns
main() main()
calls returns
Operating System Operating System

15
6th Assignment: Trapezoidal rule
y
e.g. f ( x )  x
2

f (x)
f (xi )
f (xi+1 )
b

I   f ( x ) dx
a

a xi xi+1 b x
1
Ai   f ( x i 1 )  f ( x i )  ( x i 1  xi )
2

1 n 1
1 
 T  h  f ( x0 )   f ( x j )  f ( xn )
2 
 j 1 2 

16
Input number of subintervals n
interval a,b

Computation step size h=(b-a)/n


trapezoidal rule
1 n 1
1 
T  h  f (x0 )   f (x j )  f ( x n )
2 j 1 2 

T = 0.5 * ( f(a) + f(b) ); // x(0) und x(n)


for(i=1; i<n; i++) // loop x(1)...x(n-1)
{
T += f( a + i*h );
}
T = T * h;

Output of T approximating the definite integral

17
Variables, pointers and addresses
Motivation: Call by value

Change of the values of parameters

is performed within the but not


called function within the calling function

reason

When a function is called, a (local) copy of all parameters


Function call is made and only this copy is modified. This transfer of
parameters is a call by value.

18
Call by value

in t q u a d ( in t i)
{
i = i * i;
r e t u r n i;
}

v o id m a i n ( )
{
in t n , q ;
n = 3;
q = q u a d ( n ) ; / / n is c o p ie d t o a n e w v a r ia b le a n d g iv e n t o q u a d
/ / v a lu e o f n is s t ill 3
p r in t f ( “ b a s is % d , s q u a r e % d \ n “ , n , q ) ;
}

Example: 7_b
19
Call by value

v o id m a i n ( )
{ in t q u a d ( in t i)
in t n , q ; {
n = 3; i = i * i;
q = q u a d (n ); r e t u r n i;
p r in t f ( “ b a s is % d , s q u a r e % d \ n “ , n , q ) ; }
}

n Copy i
At the call: 3 3
Computation
In the Function: 9
Copy
n q
At the return: 3 9

20
Question: How can we get that a function returns more than one value?

Function Function
??
o.k.

Answer: Use memory adresses (so-called pointers).


Using memory addresses as parameters, it is yet possible to change the value
of more than one variable.
This is possible, since a modification in the contents of a memory address does
not change the address itself.
21
How are variables stored in memory?
Remember this … ? Memory is like a shelf!

Every variable has a unique identifier specifying its place in the memory:
the address!

22
Variables, pointers and addresses

A variable has the following characteristics:

• A memory address, where


• the value of the variable is stored, and
• a name, allowing to access the memory contents of the variable.

• The data type defines, how many bits are reserved for the data and
how the sequence of bits has to be interpreted.

C++ (like C) can control all these aspects of a variable (within certain limitations).

23
Different operators are defined for accessing variables
Reference operator (&)
A reference operator can be used to obtain an address of a variable.

Given following example:

Int andy;
Int fred;
Int ted;

andy = 25;
fred = andy;
ted = &andy;

24
Different operators are defined for accessing variables
Dereference operator (*)
A dereferencing operator gets the value of a given address.
See the following example:

Int beth;
beth = *ted;

“beth equal to value pointed


by ted"

Notice the difference between the reference and dereference operators:


• & is the reference operator and can be read as "address of"
• * is the dereference operator and can be read as "value pointed by”

25
Definition of a new Datatype called „Pointer“

A pointer is a variable type that is designed to store addresses (references).

It is defined as follows:

<type>* <name>;
e.g.
int* points_to_integer;

With the help of pointers you can directly store addresses instead of
dereferencing variables to retrieve the address.

For more complex data tyes (like arrays) it is a lot easier to pass the starting
address than to copy each element into one function.

26
Summary and Examples

int a; Declaration of an int-variable named a


This defines that adequate memory space for one int-variable
named a is available.

int* pointer_a; Declaration of a pointer variable which can store


the address of an integer variable
(dereference operator *)

pointer_a = &a; assigns the actual address of a to the pointer variable


pointer_a.
b = *pointer_a; the contents of the address stored in pointer_a is read and
copied to the memory space reserved for b
(* is called de-reference operator)
*pointer_a = 3; Insert the value 3 in that memory address which is indicated by
the pointer pointer_a.

27
Exercise for practicing referencing and dereferencing operators

28
Concept of a reference

A reference is a declaration of a synonymous name for an object.

int d; Declaration of an int-variable named d

int& r_d=d; everything that will be done with reference r_d


refers to the object d

r_d=10; modifies the contents of variable d (and only


this) to fit into the int-value 10

Example: 7_c
29
Transfer of parameters to functions

Call by Value Call by Reference

v o id m a in ( )
{
in t i ;
in t j ; v o id f ( in t v a l, in t& r e f)
i = 1; {
j = 2; v a l+ + ;
f ( i, j) ; r e f+ + ;
} }

ref
i j val
Memory at call: 1 2 1

Example: 7_d, 7_e Copy


30
Call by value for pointers
To modify a value it is sufficient to indicate the address where the contents of the
memory are to be changed:

void polar(double x1, double y1, double x2, double y2, double* l, double* w)
{
*l = length(x1, y1, x2, y2);
*w = angle(x1, y1, x2, y2);
return;
}

void main()
{
double l,w;
double u1, v1, u2, v2;
….
polar(u1, v1, u2, v2, &l, &w);
….

31
Summary – Different possibilities for function calls

There are three different possibilities to transfer your variables to


functions:
• call by value: pass the value of a variable
• call by reference: pass the address of a variable
• call by value for pointers: pass the value of a pointer  pass
the address of a variable the pointer points to

32
Example of the three different ways
Call by value :
void polar_value(double x1, double y1, double x2, double y2, double l, double w)
{
l = length(x1, y1, x2, y2); Call to this function :
w = angle(x1, y1, x2, y2); polar(u1, v1, u2, v2, l, w);
return;
}

Call by reference :
void polar_ref_2(double x1, double y1, double x2, double y2, double& l, double& w)
{
l = length(x1, y1, x2, y2); Call to this function :
w = angle(x1, y1, x2, y2); polar(u1, v1, u2, v2, l, w);
return;
}

Call by value for pointers : Example:


void polar_ref(double x1, double y1, double x2, double y2, double* l, double* w) 7_f
{
*l = length(x1, y1, x2, y2); Call to this function :
*w = angle(x1, y1, x2, y2); polar(u1, v1, u2, v2, &l, &w);
return;
}
33
7th Assignment
// bubble sort
for( k=1; k<n; k++ ) Example with n=4
{ a0 a1 a2 a3
for( j=n-1; j>=k; j-- ) 17 3 30 12
{
if( ar[j-1]>ar[j] ) k=1, j=3 17 3 12 30
{
// swap j=2 17 3 12 30
temp=ar[j-1]; j=1 3 17 12 30
ar[j-1]=ar[j];
swap(...)
ar[j]=temp; k=2, j=3 3 17 12 30
}
j=2 3 12 17 30
// output of each step
printf("\nK=%d, J=%d ",k,j);
for(i=0; i<n; i++) k=3, j=3 3 12 17 30
printf("%2d ",ar[i]);
}
}
34

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy