en - 01+02 - introducere. subprograme (cont)

39
Algorithms and programming techniques ? ? ? ?

Upload: bicajanu-bianca

Post on 12-Sep-2015

234 views

Category:

Documents


1 download

TRANSCRIPT

Introducere. Subprograme (cont.)

Algorithms and programming techniques????

Discipline chart (programare.ase.ro, ATP page)Content, prerequisitesBibliography manual, solved problems bookEvaluationSeminar: 40%Mandatory homework (prerequisite for practical test): 10%Practical test: 30% Examination: 50%Ex officio: 10%MiscelaneousPresence, recuperation, individual study, rules, collaboration ConsultationsRoom 2301, Thursday 13:30-14:50, Friday 9:00-10:20

Algorithms and programming techniques

Subprograms (continued)Pointers to functions (subprograms)RecursivitySubprogram 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 Typepointer to a subprogram that receives a specific list of inputs and returns a specific resultUseDynamic call of subprograms, transmission of subprograms as parameters to other subprograms

Pointers to functions (subprograms)Examplevoid 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)ExampleBisection method for solving an equation

x1x2n, epsxf(x)

Pointeri la funcii (subprograme)#include

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) iterative / recursive functionRecursive function: calls itself (at least once)Direct recursivity SimpleMultipleMutual recursivity

ImplicationsFunction constructionMemory requirements

Recursivity, recursive functionsConstruction of recursive functionsMake sure the algorithm is finite: ends after a finite number of iterationsEach call must solve a simpler problem than current iterationStop when current problem is trivialCondition to stop recursive callsApply start formula if the condition is confirmedApply recursive formula otherwise

long fact ( unsigned n ){ long f; if ( !n ) f = 1; else f = n*fact ( n-1); return f;}

Recursivity, recursive functionsMemory requirements

Recursivity, recursive functionsfib(n) = fib(n-1) + fib(n-2), fib(1) = fib(0) = 1fib( 4 )fib( 3 )fib( 0 )fib( 1 )fib( 2 )63211fib( 1 )1fib( 2 )11fib( 1 )fib( 0 )2

Recursivity, recursive functionsChoosing iterative / recursive functions?Advantages and drawbacks

Memory use

Processor time

Ease of design / implementationLength of source code

Recursivity, recursive functionslong 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 functionsSum of an arrays elementsS(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 arrays elements

Recursivity, recursive functionsBinary 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 functionsTransform an iterative function into a recursive oneRemove iterative instruction (for, while, do)Iterative condition becomes (perhaps changed) the condition to stop recursive callsRepetition is performed by a self call

Example: bisection method

Recursivity, recursive functionsMetoda biseciei

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) General > Additional Include Directories > calea ctre matrice.hProject > Set As StartUp ProjectSe compileaz soluia (Build)Se lanseaz n execuie din IDE sau separatTest.exe se afl n BSIDE\Debug

Biblioteci de subprograme: staticen IDE utilizare bibliotec binar n alt soluieSe creeaz un proiect nou de tip Win32 Console Application numele soluiei (i al proiectului): TestSn fereastra Application settings se alege Application type: Console ApplicationAdditional options: Empty project, fr Precompiled headersSe adaug la proiect fiierul surs (cu funcia main)Se copiaz n directorul proiectului fiierele matrice.h i matrice.libProject > Properties > Configuration Properties > Linker > Input > Additional Dependencies > se adaug matrice.libSe compileaz soluia (Build)Se lanseaz n execuie

Dynamic librariesFunction code is separated from the main program

File extensionWindows: .dllLinux: .so

AdvantagesSmaller executableThe library is shared by several applications

DrawbacksSeveral files (main executable + dynamic libraries)Additional processing timeLibrary must be on the search path or current folder

Biblioteci de subprograme: dinamiceEditare de legturiFiiere cod surs(.c, .cpp, .h)Fiiere cod obiect (.obj)Tabela de import (.lib)Biblioteci dinamice(.dll)Fiiere cod surs(.c, .cpp, .h)Cod binar executabil(.exe)CompilareEditare de legturiBiblioteci cod obiect(.lib)Fiiere cod obiect(.obj)CompilareCod binar executabil(.exe)Biblioteci dinamice(.dll)

Biblioteci de subprograme: dinamiceCrearea i utilizarea este asemntoare cu a bibliotecilor statice

DifereneAntetul funciilor trebuie s conin (doar n .h)__declspec(dllexport)

La execuie, fiierul .dll trebuie s poat fi gsit (cale cunoscut)

Biblioteci de subprograme: dinamicen mod comandSe creeaz un director nou pentru proiect n care se salveaz cele 3 fiiereSe execut vcvars32.bat, aflat in subdirectorul bin al Visual StudioC:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin

cl matrice.cpp /LDmatrice.dll, matrice.lib

cl test.cpp matrice.libtest.exe

Pentru execuie snt necesare:text.exe i matrice.dll

Biblioteci de subprograme: dinamicen IDE creare bibliotec binarSe creeaz un proiect nou de tip Win32 Console Application numele soluiei: BDIDE, al proiectului: matrice

n fereastra Application settings se alege Application type: DLLAdditional options: Empty project

Se adaug la proiect fiierele surs (antet i implementare)

Se compileaz soluia (Build)

n directorul BDIDE\matrice\Debug se va genera biblioteca binarfiiere: matrice.dll, matrice.lib

Biblioteci de subprograme: dinamicen IDE utilizare bibliotec binar n aceeai soluieSe creeaz un proiect nou de tip Win32 Console Application numele proiectului: Test, se adaug la soluia BDIDEn fereastra Application settings se alege Application type: Console ApplicationAdditional options: Empty project, fr Precompiled headersSe adaug la proiect fiierul surs (cu funcia main)Project > Properties > Common Properties > Framework and References > Add New Reference > matriceProject > Properties > Configuration Properties > C/C++ > General > Additional Include Directories > calea ctre matrice.hProject > Set As StartUp ProjectSe compileaz soluia (Build)Se lanseaz n execuie

Biblioteci de subprograme: dinamicen IDE utilizare bibliotec binar n alt soluieSe creeaz un proiect nou de tip Win32 Console Application numele soluiei (i al proiectului): TestDSe copiaz n directorul proiectului fiierele matrice.h i matrice.libn fereastra Application settings se alege Application type: Console ApplicationAdditional options: Empty project, fr Precompiled headersSe adaug la proiect fiierul surs (cu funcia main)Project > Properties > Configuration Properties > Linker > Input > Additional Dependencies > se adaug matrice.libProject > Properties > Configuration Properties > Debugging > Environment > se adaug calea ctre matrice.dllSe compileaz soluia (Build)Se lanseaz n execuie

Biblioteci de subprograme: dinamiceComparaie dimensiuni: T E M !

Cnd folosim biblioteci?

Cnd folosim biblioteci statice / dinamice?Static (.lib)Dinamic (.dll)L.C.IDEL.C.IDEmatrice.h? ? ? ? matrice.lib????matrice.dll--??test.exe????

Biblioteci de subprograme: dinamiceTemCreai i testai o bibliotec format din funciile necesare prelucrrii vectorilorBibliotec staticLucrai n mod comandLucrai n IDEBibliotec dinamicLucrai n mod comandLucrai n IDE

Spor la nvat!

caller

fact(3)

t1

2 * fact(1)

t2

fact(1)

t3

1 * fact(0)

t4

t5

fact(0)

fact(3)

3*fact(2)

fact(2)

1

1*1=1

t6

2*1=2

t7

3*2=6

t8

6

Stack

Return address3f

t1

t2

t3

t4

t5

t6

t7

t8

Return address2f

Return address1f

Return address0 f