Introducere. Subprograme (cont.)

Download Report

Transcript Introducere. Subprograme (cont.)

?? ?
?
Algorithms and programming techniques

Discipline chart (programare.ase.ro, ATP page)
 Content, prerequisites
 Bibliography – manual, solved problems book
 Evaluation
▪ Seminar: 40%
▪ Mandatory homework (prerequisite for practical test): 10%
▪ Practical test: 30%
▪ Examination: 50%
▪ Ex officio: 10%
 Miscelaneous
▪ Presence, recuperation, individual study, rules, collaboration
 Consultations
▪ Room 2301, Thursday 13:30-14:50, Friday 9:00-10:20
Subprograms (continued)

Pointers to functions (subprograms)

Recursivity

Subprogram libraries
Pointers to functions (subprograms)
The name of a function can be used as a
constant pointer
 Meaning

 The memory address where the executable code of the
function is located

Type
 pointer to a subprogram that receives a specific list of
inputs and returns a specific result

Use
 Dynamic call of subprograms, transmission of
subprograms as parameters to other subprograms
Pointers to functions (subprograms)

Example
void sortare(float v[], int n);
sortare  pointer to a function that receives a vector of float and an
int and returns void result
float minim(float v[], int n, int poz[], int* nr);
minim  pointer to a function that receives a vector of float, an int, a
vector of int and a pointer to and returns a float result
Pointers to functions (subprograms)

Variable / parameter of type pointer to function
void sortare(float v[], int n);
float minim(float v[], int n, int poz[], int* nr);
void main()
{ int dim; float a[100]; int unde[100], cite;
void (*p)(float v[], int n);
float (*q)(float v[], int n, int poz[], int* nr);
…
p = sortare;
q = minim;
sortare(a,dim); //  (*p)(a, dim);
p(a, dim);
minim(a,dim,unde,&cite);
//  (*q)(a,dim,unde,&cite);
…
}
Pointers to functions (subprograms)

Example
 Bisection method for solving an equation
f(x)
n, eps
x1
x
x2
Pointeri la funcții (subprograme)
#include <stdio.h>
float ecuatie(float x)
{ return x*x - 7*x + 12;
}
int bisectie( float x1, float x2,
float eps, int n,
float (*f)(float),
float *x)
{ int cod = 0;
while ((n > 0) && (cod == 0))
{ *x = (x1 + x2) / 2;
if((*f)(*x) == 0)
cod = 1;
else
if((x2-x1) < eps)
cod = 2;
else
if((*f)(x1)*(*f)(*x)<0)
x2 = *x;
else
x1 = *x;
n--;
}
return cod;
}
void main()
{ float a, b, sol, prec;
int nr, cod;
printf("\na="); scanf("%f",&a);
printf("\nb="); scanf("%f",&b);
printf("\nprecizia=");
scanf("%f",&prec);
printf("\nnr="); scanf("%d",&nr);
cod = bisectie(a,b,prec,nr,ecuatie,&sol);
}
switch(cod)
{ case 0: printf("\nFara solutie");
break;
case 1: printf("\nSolutia exacta este
%7.3f", sol);
break;
case 2: printf("\nSolutia aproximativa
este %7.3f", sol);
}
Recursivity


Iterative algorithms
Recursive algorithms
 Simple recursivity (uni-recursive algorithm)
 Multiple recursivity (multi-recursive algorithm)
 Start formula (on or more)
 Recursive formula

Examples




Count the value that comply to a condition
Sum of an array’s elements
Euclid’s algorithm
Fibonacci string
Recursivity, recursive functions


Iterative / recursiv algorithm => iterative / recursive function
Recursive function: calls itself (at least once)
 Direct recursivity
▪ Simple
▪ Multiple
 Mutual recursivity

Implications
 Function construction
 Memory requirements
Recursivity, recursive functions

Construction of recursive functions
 Make sure the algorithm is finite: ends after a finite number of iterations
▪
Each call must solve a simpler problem than current iteration
▪
Stop when current problem is trivial
 Condition to stop recursive calls
▪ Apply start formula if the condition is confirmed
▪ Apply recursive formula otherwise
long fact ( unsigned n )
{ long f;
if ( !n )
f = 1;
else
f = n*fact ( n-1);
return f;
}
Recursivity, recursive functions
caller

Memory requirements
fact(3)
t1
fact(3)
3*fact(2)
t2
fact(2)
t1
t2
t3
t4
Stack
Return address
3
f
Return address
2
f
Return address
1
f
Return address
0
f
2 * fact(1)
t3
fact(1)
t8
1 * fact(0)
t7
t4
fact(0)
1
t6
1*1=1
t5
2*1=2
3*2=6
6
t8
t7
t6
t5
Recursivity, recursive functions
fib(n) = fib(n-1) + fib(n-2), fib(1) = fib(0) = 1
fib( 4 )
fib( 3 )
fib( 2 )
fib( 1 )
1
fib( 0 )
1
2
fib( 1 )
1
3
fib( 2 )
2
6
fib( 1 )
1
fib( 0 )
1
Recursivity, recursive functions

Choosing iterative / recursive functions?
 Advantages and drawbacks
▪ Memory use
▪ Processor time
▪ Ease of design / implementation
▪ Length of source code
Recursivity, recursive functions

Combination calculation (k items out of n options)
𝑛!
𝑘
𝑘−1
𝐶𝑛𝑘 =
=>
𝐶𝑛𝑘 = 𝐶𝑛−1
+ 𝐶𝑛−1
, 𝐶𝑛0 = 1 𝐶𝑛𝑛 = 1
𝑘! 𝑛−𝑘 !
long comb(unsigned n, unsigned k)
{ long c;
if (k>n)
c = 0;
else
if ((k==0)||(k==n))
c = 1;
else
c = comb(n-1,k) + comb(n-1,k-1);
return c;
}
Recursivity, recursive functions


Sum of an array’s elements
S(n) = x[n-1] + S(n-1),
S(0) = 0
double suma(double v[], int n)
{ double s;
if( n == 0)
s = 0;
else
s = v[n-1] + suma(v, n-1);
return s;
}

Product of an array’s elements
Recursivity, recursive functions

Binary search
int cauta(float v[], int p, int u, float k)
{ int m;
if (p > u)
m = -1;
else { m = (p + u) / 2;
if(k < v[m])
m = cauta(v, p, m-1, k);
else
if(k > v[m])
m = cauta(v, m+1, u, k);
}
return m;
}
Recursivity, recursive functions

Transform an iterative function into a recursive one
1. Remove iterative instruction (for, while, do)
2. Iterative condition becomes (perhaps changed) the condition to
stop recursive calls
3. Repetition is performed by a self call

Example: bisection method
Recursivity, recursive functions
int bisectie( float x1, float x2, float eps, int n, float
 Metoda bisecției
(*f)(float),
float *x)
{ int
int cod;
bisectie( float x1, float x2, float eps, int n,
if ( n == 0 )
float (*f)(float), float *x)
0; = 0;
{ cod
int =cod
else
while
> 0)
&& (cod == 0))
{ *x
= (x1((n
+ x2)
/ 2;
{ *x = (x1 ==
+ x2)
if((*f)(*x)
0) / 2;
if((*f)(*x)
== 0)
cod
= 1;
else cod = 1;
else
if((x2-x1) < eps)
if((x2-x1) < eps)
cod cod
= 2;= 2;
else
else
{ if( if((*f)(x1)*(*f)(*x)<0)
(*f)(x1) * (*f)(*x) < 0 )
x2 =x2*x;
= *x;
elseelse
= *x;
x1 =x1*x;
n--;
n--;
} cod = bisectie( x1, x2, eps, n, f, x );
return
cod; if((*f)(x1)*(*f)(*x)<0)
}
}
cod = bisectie( x1, *x, eps, n-1, f, x );
return cod;
else cod = bisectie( *x, x2, eps, n-1, f, x );
}
Recursivity, recursive functions

Homework:
Count
the number of negative elements of an array
Scalar
multiplication of 2 arrays
Euclid’s
algorithm
Greatest
Tangent
Hanoi
Sort
common factor
method for solving equations
towers
an array
Libraries

Library: collection of functions, in a compiled file (object)

Purpose
 Code reuse for multiple applications
 Distribution to other users

Types
 Source code, binary (object) code
 Static, dynamic
Libraries

Work options
 Command line
▪ cl.exe
▪ lib.exe
▪ link.exe
- compiler
- library manger
- link editor
 In IDE (Visual Studio)
▪ Same solution (with multiple projects)
▪ Separate solutions
Static libraries

Function code is inserted into the program

File extension
 Windows:
 Linux:

.lib
.a
Advantages
 Single executable file
 Only called functions are extracted from the library and inserted
in the program

Drawbacks
 Larger executable file
 Each executable includes a separate copy of the same functions
Static libraries
Source
code
(.c, .cpp, .h)
Source
code files
(.c, .cpp, .h)
Compile
Object code
(.obj)
Compile
Object code
(.obj)
Library
manager
Link editor
Object code
library
(.lib)
Object code
library
(.lib)
Executable
file
(.exe)
Static libraries
#include <stdio.h>
#include <malloc.h>
//alocare
dinamica matrice
#include
"matrice.h"
// I - nr. linii, nr. coloane
// E - adresa
//citire
matricematricei
patrata cu alocare
//
I - **aloca_matrice(int m, int n);
double
// E - adresa matrice, dimensiune
double**
citire_matrice(int
*m)
//dezalocare
matrice dinamica
{//int
i,j;
I - adresa matricei, nr. linii
a;
//double**
E - adresa
matricei (NULL)
printf_s("\n\nDimensiune: ");
#include double**
<stdio.h> dezalocare_matrice(double **a, int m);
scanf_s("%d",m);
#include <conio.h>
a=new double*[*m];
#include //produs
"matrice.h"
matrice patrate de dimensiuni egale, prealocate
for(i=0;i<*m;i++)
// Ia[i]=new
- a, b,double[*m];
n
void main()
//for(i=0;i<*m;i++)
E - c
{ double** a;
voidfor(j=0;j<*m;j++)
produs_mpn(double** a, double **b, int n, double** c);
int m,n;
{ printf_s("a[%d,%d]= ",i,j);
scanf_s("%lf",&a[i][j]);
//copiaza matrice prealocate
a=citire_matrice(&m);
// I - a, m, }n
afisare_matrice(a,m);
return a;
// E - b
}
_getch();
void copiaza(double** a, int m, int n, double** b);
}
//afisare matrice patrata
//citire
matrice
patrata
cu alocare
//
I - adresa
matrice,
dimensiune
// EI -//
// E afisare_matrice(double**
- adresa matrice, dimensiune
void
a, int m)
{double**
int i,j; citire_matrice(int *m);
//cout<<"\nMatricea este: \n";
for(i=0;i<m;i++)
//afisare
matrice patrata
//{ Ifor(j=0;j<m;j++)
- adresa matrice, dimensiune
printf_s("%10.6lf ",a[i][j]);
// E printf_s("\n");
void
afisare_matrice(double** a, int m);
}
printf_s("\n");
}

Fișiere sursă
 antet
 implementare
 test
matrice.h
matrice.cpp
test.cpp
Static libraries

Command line
 Create a new folder and save the required files
 Run vcvars32.bat, found in Visual Studio’s folder bin
▪ C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin

cl -c matrice.cpp
▪ matrice.obj

lib matrice.obj /out:matrice.lib
▪ matrice.lib

cl test.cpp matrice.lib
▪ test.exe
Static libraries

In IDE – create binary library
 Create a new project, Win32 Console Application
▪ solution name: BSIDE, project name: matrice
 In Application settings dialog choose
▪ Application type: Static library
▪ Additional options: Empty project, no Precompiled headers
 Add source files to the project (header and implementation)
 Compile solution (Build)
 The library is created in folder BSIDE\Debug
▪ Library name: matrice.lib
Biblioteci de subprograme: statice

În IDE – utilizare bibliotecă binară în aceeași soluție
 Se creează un proiect nou de tip Win32 Console Application







▪ numele proiectului: Test, se adaugă la soluția BSIDE
În fereastra Application settings se alege
▪ Application type: Console Application
▪ Additional options: Empty project, fără Precompiled headers
Se adaugă la proiect fișierul sursă (cu funcția main)
Project > Properties > Common Properties > Framework and
References > Add New Reference… > matrice
Project > Properties > Configuration Properties > C/C++ > General >
Additional Include Directories > calea către matrice.h
Project > Set As StartUp Project
Se compilează soluția (Build)
Se lansează în execuție din IDE sau separat
▪ Test.exe se află în BSIDE\Debug
Biblioteci de subprograme: statice

În IDE – utilizare bibliotecă binară în altă soluție
 Se creează un proiect nou de tip Win32 Console Application






▪ numele soluției (și al proiectului): TestS
În fereastra Application settings se alege
▪ Application type: Console Application
▪ Additional options: Empty project, fără Precompiled headers
Se adaugă la proiect fișierul sursă (cu funcția main)
Se copiază în directorul proiectului fișierele matrice.h și matrice.lib
Project > Properties > Configuration Properties > Linker > Input >
Additional Dependencies > se adaugă matrice.lib
Se compilează soluția (Build)
Se lansează în execuție
Dynamic libraries

Function code is separated from the main program

File extension
 Windows:
 Linux:

.dll
.so
Advantages
 Smaller executable
 The library is shared by several applications

Drawbacks
 Several files (main executable + dynamic libraries)
 Additional processing time
 Library must be on the search path or current folder
Biblioteci de subprograme: dinamice
Fișiere cod
sursă
(.c, .cpp, .h)
Fișiere cod
sursă
(.c, .cpp, .h)
Compilare
Fișiere cod
obiect (.obj)
Tabela de
import (.lib)
Compilare
Fișiere cod
obiect
(.obj)
Editare de
legături
Editare de legături
Biblioteci
dinamice
(.dll)
Cod binar
executabil
(.exe)
Biblioteci
cod obiect
(.lib)
Biblioteci
dinamice
(.dll)
Cod binar
executabil
(.exe)
Biblioteci de subprograme: dinamice

Crearea și utilizarea este asemănătoare cu a bibliotecilor
statice

Diferențe
 Antetul funcțiilor trebuie să conțină (doar în .h)
__declspec(dllexport)
 La execuție, fișierul .dll trebuie să poată fi găsit (cale cunoscută)
Biblioteci de subprograme: dinamice

În mod comandă
 Se creează un director nou pentru proiect în care se salvează cele 3
fișiere
 Se execută vcvars32.bat, aflat in subdirectorul bin al Visual Studio
▪ C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin

cl matrice.cpp /LD
▪ matrice.dll, matrice.lib

cl test.cpp matrice.lib
▪ test.exe
 Pentru execuție sînt necesare:
▪ text.exe și matrice.dll
Biblioteci de subprograme: dinamice

În IDE – creare bibliotecă binară
 Se creează un proiect nou de tip Win32 Console Application
▪ numele soluției: BDIDE, al proiectului: matrice
 În fereastra Application settings se alege
▪ Application type: DLL
▪ Additional options: Empty project
 Se adaugă la proiect fișierele sursă (antet și implementare)
 Se compilează soluția (Build)
 În directorul BDIDE\matrice\Debug se va genera biblioteca binară
▪ fișiere: matrice.dll, matrice.lib
Biblioteci de subprograme: dinamice

În IDE – utilizare bibliotecă binară în aceeași soluție
 Se creează un proiect nou de tip Win32 Console Application







▪ numele proiectului: Test, se adaugă la soluția BDIDE
În fereastra Application settings se alege
▪ Application type: Console Application
▪ Additional options: Empty project, fără Precompiled headers
Se adaugă la proiect fișierul sursă (cu funcția main)
Project > Properties > Common Properties > Framework and
References > Add New Reference… > matrice
Project > Properties > Configuration Properties > C/C++ > General >
Additional Include Directories > calea către matrice.h
Project > Set As StartUp Project
Se compilează soluția (Build)
Se lansează în execuție
Biblioteci de subprograme: dinamice

În IDE – utilizare bibliotecă binară în altă soluție
 Se creează un proiect nou de tip Win32 Console Application







▪ numele soluției (și al proiectului): TestD
Se copiază în directorul proiectului fișierele matrice.h și matrice.lib
În fereastra Application settings se alege
▪ Application type: Console Application
▪ Additional options: Empty project, fără Precompiled headers
Se adaugă la proiect fișierul sursă (cu funcția main)
Project > Properties > Configuration Properties > Linker > Input >
Additional Dependencies > se adaugă matrice.lib
Project > Properties > Configuration Properties > Debugging >
Environment > se adaugă calea către matrice.dll
Se compilează soluția (Build)
Se lansează în execuție
Biblioteci de subprograme: dinamice

Comparație dimensiuni: T E M Ă !
Statică (.lib)
Dinamică (.dll)
L.C.
IDE
L.C.
IDE
matrice.h
?
?
?
?
matrice.lib
?
?
?
?
matrice.dll
-
-
?
?
test.exe
?
?
?
?

Cînd folosim biblioteci?

Cînd folosim biblioteci statice / dinamice?
Biblioteci de subprograme: dinamice

Temă
 Creați și testați o bibliotecă formată din funcțiile necesare
prelucrării vectorilor
▪ Bibliotecă statică
▪ Lucrați în mod comandă
▪ Lucrați în IDE
▪ Bibliotecă dinamică
▪ Lucrați în mod comandă
▪ Lucrați în IDE