1 / 42

Where are we, and where to go?

Where are we, and where to go?. 2012. 1004. Procedural programming, Or structured programming, Or imperative programming (104), modularity. ( 152). OOP (104, 151 ). ( 171). Data structure: Linear: list, stack, queue Nonlinear: tree, graph. Simple types of variables

alboyd
Download Presentation

Where are we, and where to go?

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Where are we, and where to go? 2012 1004 Procedural programming, Or structured programming, Or imperative programming (104), modularity (152) OOP (104, 151) (171) Data structure: Linear: list, stack, queue Nonlinear: tree, graph Simple types of variables (variables=objects) 3 program structures (assignment, conditional, iteration) Static objects Dynamic objects Functions on objects (member) variables Array, struct pointer class objects operation (member) functions Algorithms C++, Java C, Pascal Data, variable, object Operation, function, procedure, subprogram, module, method Algorithms+Data Structures = Programs Niklaus Wirth

  2. Programming paradigms • Procedural programming • Object-oriented programming

  3. Procedural programming • An (ordered) sequence of ‘procedures’ or ‘functions’ or meta-instructions • Three instructions • Assignment • Conditional • iteration

  4. procedural programming: main(), is the first function, and is composed of a sequence of ‘procedures’ (or ‘functions’ in C++). Functions communicate by passing parameters. int main() { A a; B b; C c; a.f1(); b.f2(); c.f3(); … } Class A { Int x; Int f1(); } Class B { Int y; Int f2() } Class C { Int z; Int f3(); } int main() { int x,y,z; int a,b,c; a=f1(x); b=f2(y); c=f3(z); … } int f1() { } int f2() { } int f3() { } Object oriented programming: a sequence of ‘objects’! Objects communicate by sending messages.

  5. Math and CS • From ‘calculus’, get ‘programming fundamentals’ • Sequence, dynamic procedure • Euclid  a process or an algorithm  iteration • Approximation of a real  iteratively • ‘bracket’ the solution of a polynomial  iteration • Recurrent sequence u_{n+1} = f(u_n)  ‘recursion’ • Recurrent sequentce is ‘more expressive’, but no ‘close-form’ solution • ‘convergence’ for math  ‘termination’ of a recursive procedure or a loop • Fixed-point theorem  important for ‘recursion’ to finish • Invariance  proof of correctness of a ‘loop’ • From ‘algebra’, get ‘object-oriented programming’ • ‘algebra’ comes later than ‘calculus’ • About ‘categorization’ • Look for ‘general rules’ for the same objects • Group, ring, and fields: set of elements and operators • element sets  class • operators  operators

  6. Key concepts in procedural programming • Parameters passing • Scope of variables • Recursions • Algorithm analysis • Sorting algorithms

  7. Parameter Passing

  8. Communication between functions: • Pass by value: formal parameters and arguments are different variables. ideal desirable behavior (but not efficient some times) • Pass by reference: they are the same variables, but different names! should carefully handled! Functional programming

  9. Reference: X& • int& b a; • b is an alternative name for a void f(int& b) {}; int main() { int a; f(a); } int a=10; int& b = a; int& c = a; b = 100; a ??? int& b; a 10 b c Relationship with pointers (later on)!

  10. Call by Value int f(int x) { cout << “value of x = “ << x << endl; x = 4; } main() { int v = 5; f(v); cout << “value of v = “ << v << endl; } Output: Value of x = Value of v = • When a variable v is passed by value to a function f, its value is copied to the corresponding variable x in f • Any changes to the value of x does NOT affect the value of v • Call by value is the default mechanism for parameter passing in C++ 5 5

  11. Call by Reference poor style of writing f(int &x)! int f(int& x) { cout << “value of x = “ << x << endl; x = 4; } main() { int v = 5; f(v); cout << “value of v = “ << v << endl; } Output: Value of x = Value of v = • When a variable v is passed by reference to a parameter x of function f, v and the corresponding parameter x refer to the same variable • Any changes to the value of x DOES affect the value of v • syntax • semantics 5 4

  12. Call by Constant Reference – Practical solution! int f( const int& x ) { cout << “value of x = “ << x << endl; x = 4; // invalid } main() { int v = 5; f(v); cout << “value of v = “ << v << endl; } • Passing variable v by constant reference to parameter x of f will NOT allow any change to the value of x. • It is appropriate for passing large objects that should not be changed by the called function. • syntax • semantics

  13. Parameter Passing • Call by value • for small objects that should not be changed by the function • Call by constant reference • for large objects that should not be changed by the function • Call by reference • is appropriate for all objects that may be changed by the function, • not recommended!!! rare! Trade-off between the ‘ideal’ and ‘efficiency’!

  14. Return • return by value, • for small objects that should not be changed by the function • return by constant reference, • for large objects that should not be changed by the function • return by reference, • for all objects that may be changed by the function, • not recommended!!! rare!

  15. Scope of variables

  16. Scope of variables The scope of a declaration is the block of code where the identifier is valid for use. • A global declaration is made outside the bodies of all functions and outside the main program. It is normally grouped with the other global declarations and placed at the beginning of the program file. • A local declaration is one that is made inside the body of a function. Locally declared variables cannot be accessed outside of the function they were declared in.Local to a function (the variables in Main are also local, local to ‘main’ function) • It is possible to declare the same identifier name in different parts of the program: local to a block Some code enclosed in braces

  17. Global (local to the file) Local to functions Local to blocks int x; int main() { x=0; cout << x << endl; int x; x=1; { int x; x=2; cout << x << endl; } cout << x << endl; } void f() { int x; x=1; { int x; x=2; cout << x << endl; } cout << x << endl; } int main() { int x,y,z; … } void f() { int x; … }

  18. In a for-loop { int i; for (i=1;i<10;i++) cout << A[i]; } for (int i=1;i<10;i++) cout << A[i]; equivalent

  19. Global Variables • Undisciplined use of global variables may lead to confusion and debugging difficulties. • Instead of using global variables in functions, try passing local variables by reference. It is forbidden in structured programming!

  20. Summary Pass by value Global variable Pass by reference int MIN; void min(int,int); int main() { int x,y; cin >> x >> y >> endl; min(x,y); cout << MIN; } void min(int a, int b) { if (a<b) MIN=a; else MIN=b; } int min(int,int); int main() { int x,y,mini; cin >> x >> y >> endl; mini=min(x,y); cout << mini; } int min(int a, int b) { int m; if (a<b) m=a; else m=b; return (m); } void min(int,int,int&); int main() { int x,y,mini; cin >> x >> y >> endl; min(x,y,mini); cout << mini; } void min(int a, int b, int& m) { if (a<b) m=a; else m=b; } Bad style!!! Good style!!!

  21. Recursions: one of the most fundamental tools for algorithm design and analysisIn the previous stage of AI: List, Prolog

  22. High-school math example … • Deposit of 1000 dollars, 5% interest rate per year • The capital after 10 years? • C_0 = 1000; • C_{n+1} = C_n (1+5%);

  23. Deposit of 1000 dollars, 5% interest rate per year, (yearly management fees of 10 dollars?) • The capital after 10 years? • C_0 = 1000; • C_{n+1} = C_n (1+5%) - 10;

  24. Recursion: problem solving, therefore a programming technique The general top-down programming and problem solving: • Recursion is one way to decompose a task into smaller subtasks. • At least one of the subtasks is a smaller example of the same task. • The smallest example of the same task has a non-recursive solution. A complex problem is often easier to solve by dividing it into several smaller parts (by top-down analysis), each of which can be solved by itself, top-down analysis  decomposition into smaller tasks Example: The factorial function n! = n * (n-1) * (n-2) * ... * 1 or n! = n * (n-1)! and 1! = 1

  25. Normal (non-recursive) functions Recursive function void three(…) { … } void two (…) { three(); } void one (…) { two(…); } void main() { one(…); } int fac(int n){ int product; if(n <= 1) product = 1; else product = n * fac(n-1); return product; } void main(){ fac(3); } • Functions are calling (DIFFERENT) functions • One function (three) is the last ‘stopping function’ • … calling the SAME function ( with different parameters) … • The ‘stopping function’ is already included as a ‘condition’

  26. Recursive function A recursive function is just a function which is calling one (or more) other functions which happen to be the same!!! • Though the function is the same, ‘parameters’ are always ‘smaller’ • There is always at least one stopping case to terminate It is a kind of ‘loop’, even more powerful, as a general problem-solving technique! --- thinking recursively!

  27. The tower of Hanoi Move a stack of disks of different sizes from one rod to another through a third one: - only one disk is moved each time - always smaller ones on top of bigger ones Check any webpage!

  28. More ‘declarative’ than procedural! what vs. how // move n disks from A to C via B void tower(int n, char A, char B, char C) { if (n==1) move(1,A,C); else {tower(n-1,A,C,B); move(n,A,C); tower(n-1,B,A,C)}; } void move(int k, char X, char Y) { cout << “move disc ” << k << “ from “ << X << “ to “ Y “ << endl; }

  29. Trace tower(4,A,B,C)

  30. Everything is recursive … Linear search Length of a string Min, max of an array Selection sort Binary search: • Compare search element with middle element of the array: • If not equal, then apply binary search to half of the array (if not empty) where the search element would be.

  31. Recursion vs. Iteration (non-recursive) • A recursive solution may be simpler to write (once you get used to the idea) than a non-recursive solution. • But a recursive solution may not be as efficient as a non-recursive solution of the same problem. To iterate is human, to recurse, divine!

  32. For n elements: Start from the first element While (not yet finished) do do the current element move to the next one toto(n) If 0 or 1 element, just do it else decompose into first element and the n-1 remaining elements do the first element toto(n-1)

  33. Sum of the array Write a recursive function that takes a double array and its size as input and returns the sum of the array: if zero or one element, (trivial) sum( zero element or one element) = … ! else (decompose into 1-element and n-1 elements) sum(n elements) = sum( n-1 elements) + nth element

  34. double asum(int a[], int size){ double sum; if(size==0) sum=0; else sum=asum(a,size-1)+a[size-1]; return sum; }

  35. Product of an array Write a recursive function that takes a double array and its size as input and returns the product of the array: if zero or one element, (trivial) prod( zero element or one element) = …! else (decompose into 1-element and n-1 elements) prod(n elements) = prod(n-1 elements) * nth element

  36. double aprod(int a[], int size) { doulbe prod; if(size==0) prod=1; else prod=aprod(a,size-1)*a[size-1]; return prod; }

  37. Linear search Input: an array of integers A, and a value Output: the position of the value in the array if one element, check it! else decompose into 1-element and n-1 elements check the 1-element search(n-1)

  38. int search(int A[], int size, int value) { int pos; if (size==1) if(A[size-1]==value) pos=1; else pos=-1; else if(A(size-1]==value) pos=size-1; else pos=search(A,size-1,value); return pos; }

  39. Binary search Input: a sorted array of integers A, and a value Output: the position of the value in the array if the middle element == value, done! else if the middle element > value do the same in the first half of the array else do the same in the second half of the array }

  40. Recursive binary search int bsearch(int data[],lower,upper,value) { int pos; if (lower<=upper) { mid=(lower+upper)/ 2; if (data[mid] == value) pos=mid; else if (data[mid]>value) pos=bsearch(data,lower,mid–1,value); else pos=bsearch(data,mid+1,upper,value); } return pos; }

  41. (iterative) Binary search: int bsearch(int data[], int size, int value) { int lower, middle, upper; bool found; lower = 0; upper = size - 1; found=false; position=-1; while ((lower<=upper) && (!found)) { middle = (lower+upper)/2; if (data[middle] == value) { found=true; position=middle; } else { if (data[middle] > value) upper = middle - 1; else lower = middle + 1; } } return position; } int main() { const int size=8; int data[size] = {1,5,6,7,9,10,17,30}; int value; cin >> value; cout << “position of the value is “ << bsearch(data,size,value) << endl; }

  42. Sorting Take the minimum, then sort the remaining elements …

More Related