Sie sind auf Seite 1von 39

?? ?

Algorithms and
programming techniques

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

x2

Pointeri la funcii (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 arrays elements
Euclids 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

Memory requirements

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)


=>
,

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 arrays 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 arrays 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 (*f)
Metoda
biseciei
(float),
float
*x)
{ int cod;
int( bisectie(
float x1, float x2, float eps, int n,
if
n == 0 )
float (*f)(float), float *x)
cod
=
0;
{ int cod = 0;
else
{ *x
= (x1((n
+ x2)
/ 2;
while
> 0)
&& (cod == 0))
if((*f)(*x)
==
0)
{ *x = (x1 + x2) / 2;
cod
if((*f)(*x)
= 1;
== 0)
else cod = 1;
else
if((x2-x1)
< eps)
if((x2-x1)
< eps)
cod = 2;
else cod = 2;
else
{ if( if((*f)(x1)*(*f)(*x)<0)
(*f)(x1) * (*f)(*x) < 0 )
x2 =x2*x;
= *x;
elseelse
x1 =x1*x;
= *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

Euclids

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
- compiler
lib.exe
- library manger
link.exe - 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

Fiiere

surs

// E - adresa
//citire
matricematricei
patrata cu alocare
//
I
double **aloca_matrice(int m, int n);
// E - adresa matrice, dimensiune
double**
citire_matrice(int
*m)
//dezalocare
matrice dinamica
{//int
i,j;
I - adresa matricei, nr. linii
double** a;
// 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
// E - printf_s("%10.6lf ",a[i][j]);
printf_s("\n");
void
afisare_matrice(double** a, int m);
}
printf_s("\n");
}

antet
matrice.h
implementare matrice.cpp
test

test.cpp

Static libraries

Command line
Create a new folder and save the required files
Run vcvars32.bat, found in Visual Studios 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 aceeai soluie


Se creeaz un proiect nou de tip Win32 Console Application

numele proiectului: Test, se adaug la soluia BSIDE


n fereastra Application settings se alege
Application type: Console Application
Additional options: Empty project, fr Precompiled headers
Se adaug la proiect fiierul surs (cu funcia main)
Project > Properties > Common Properties > Framework and References
> Add New Reference > matrice
Project > Properties > Configuration Properties > C/C++ > General >
Additional Include Directories > calea ctre matrice.h
Project > Set As StartUp Project
Se compileaz soluia (Build)
Se lanseaz n execuie din IDE sau separat
Test.exe se afl n BSIDE\Debug

Biblioteci de subprograme: statice

n IDE utilizare bibliotec binar n alt soluie


Se creeaz un proiect nou de tip Win32 Console Application

numele soluiei (i al proiectului): TestS


n fereastra Application settings se alege
Application type: Console Application
Additional options: Empty project, fr Precompiled headers
Se adaug la proiect fiierul surs (cu funcia main)
Se copiaz n directorul proiectului fiierele matrice.h i matrice.lib
Project > Properties > Configuration Properties > Linker > Input >
Additional Dependencies > se adaug matrice.lib
Se compileaz soluia (Build)
Se lanseaz n execuie

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

Fiiere cod
surs
(.c, .cpp, .h)
Fiiere cod
surs
(.c, .cpp, .h)

Compilare

Fiiere cod
obiect (.obj)
Tabela de
import (.lib)

Compilare

Fiiere cod
obiect
(.obj)

Editare de
legturi

Editare de legturi

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 asemntoare cu a bibliotecilor


statice

Diferene
Antetul funciilor trebuie s conin (doar n .h)
__declspec(dllexport)
La execuie, fiierul .dll trebuie s poat fi gsit (cale cunoscut)

Biblioteci de subprograme: dinamice

n mod comand
Se creeaz un director nou pentru proiect n care se salveaz cele 3

fiiere
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 execuie snt 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 soluiei: BDIDE, al proiectului: matrice


n fereastra Application settings se alege

Application type: DLL


Additional 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 binar

fiiere: matrice.dll, matrice.lib

Biblioteci de subprograme: dinamice

n IDE utilizare bibliotec binar n aceeai soluie


Se creeaz un proiect nou de tip Win32 Console Application

numele proiectului: Test, se adaug la soluia BDIDE


n fereastra Application settings se alege
Application type: Console Application
Additional options: Empty project, fr Precompiled headers
Se adaug la proiect fiierul surs (cu funcia main)
Project > Properties > Common Properties > Framework and References
> Add New Reference > matrice
Project > Properties > Configuration Properties > C/C++ > General >
Additional Include Directories > calea ctre matrice.h
Project > Set As StartUp Project
Se compileaz soluia (Build)
Se lanseaz n execuie

Biblioteci de subprograme: dinamice

n IDE utilizare bibliotec binar n alt soluie


Se creeaz un proiect nou de tip Win32 Console Application

numele soluiei (i al proiectului): TestD


Se copiaz n directorul proiectului fiierele matrice.h i matrice.lib
n fereastra Application settings se alege
Application type: Console Application
Additional options: Empty project, fr Precompiled headers
Se adaug la proiect fiierul surs (cu funcia main)
Project > Properties > Configuration Properties > Linker > Input >
Additional Dependencies > se adaug matrice.lib
Project > Properties > Configuration Properties > Debugging >
Environment > se adaug calea ctre matrice.dll
Se compileaz soluia (Build)
Se lanseaz n execuie

Biblioteci de subprograme: dinamice

Comparaie dimensiuni: T E M !
Static (.lib)
matrice.h

Dinamic (.dll)

L.C.

IDE

L.C.

IDE

matrice.lib

matrice.dll

test.exe

Cnd folosim biblioteci?

Cnd folosim biblioteci statice / dinamice?

Biblioteci de subprograme: dinamice

Tem
Creai i testai o bibliotec format din funciile necesare

prelucrrii vectorilor
Bibliotec static
Lucrai n mod comand
Lucrai n IDE

Bibliotec dinamic
Lucrai n mod comand
Lucrai n IDE

Spor la nvat!

Das könnte Ihnen auch gefallen