1 / 109

Data Structures and Algorithms

Data Structures and Algorithms. What is Abstraction?. What is abstraction?. In general terms a computer is nothing but a lot of on/off switches (i.e. 0/1). We can manipulate data by changing or evaluating state. We can perform addition, subtraction, and logic analysis.

julie
Télécharger la présentation

Data Structures and Algorithms

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. Data Structures and Algorithms What is Abstraction?

  2. What is abstraction? • In general terms a computer is nothing but a lot of on/off switches (i.e. 0/1). • We can manipulate data by changing or evaluating state. We can perform addition, subtraction, and logic analysis. • We can manipulate where data is stored thru registers and addresses.

  3. What is abstraction? • We make successive abstractions from the state of an on/off value all the way through solving complex problems. Binary hex op code (machine instructions) assembly language 01110100101… 0xeb\0x2a\0x89\0xcd\…. pushl EBP\popl ESI\jmp 0x2a High level language real world problem int a = 3;\int b = a + 1; x = 3 + 1

  4. Abstraction • Every algorithm depends on: • Data: information manipulated by the algorithm • Control flow: order in which instructions are executed

  5. Abstraction in Programming • Naming -- using descriptive identifiers to denote variables, constants, and complicated data types. • Top-Down Design -- designing an algorithm by decomposing a problem into subproblems, then decomposing each subproblem, etc. • Functional Abstraction -- invoking a function to carry out a task without knowing its implementation (mechanism for accomplishing the result). • Data Abstraction -- separating properties of a data type (its values and operations) from its implementation.

  6. Abstraction • Computers execute low level instructions. • Difficult to understand • Readability is non-existent • Debugging is very difficult • Based on three types of operations • Unconditional Branch • Conditional Branch • Sub Routine call • Control structures used in modern languages can implement these in terms of • if, if – else, if – then – else, and switch operations • do – while, and while operations • functions and procedures

  7. Control Abstraction • Algorithms are divided into two parts • Data Manipulation: How the data is used within the algorithm • Control Flow: The order in which the instructions are executed • Two forms of control Abstraction • Control Structures: abstraction to low-level machine instructions • Functions & Procedures: abstract multiple actions as single actions. • The distinction between control and data abstraction is fuzzy. The reason is that data abstractions normally include control abstraction.

  8. . . . Statement Statement Statement Control Abstraction • Control Flow -- the order in which instructions are executed. • Instructions are normally executed in sequence, one after the other. • To alter this, high-level languages, like C++ use special instructions called control structures for selection, looping and termination.

  9. 160 IF I >= J GO TO 163 161 LET I = I + 3 162 GO TO 160 163 LET K = 5 while (i < j) i = i + 3; k = 5; 500 IF I <= J GO TO 503 501 LET A = 20 502 GO TO 504 503 LET A = 30 504 LET B = 2 * a if (i > j) a = 20; else a = 30; b = 2 * a; 200 LET I = 0 201 LET A = 0 202 IF I >= 10 GO TO 205 203 LET A = A + 2 204 LET I = I + 1 205 GO TO 202 206 LET B = A a = 0; for (i = 0;i < 10;i++) a = a + 2; b = a; Compare

  10. Control Structures for • Selection if, if . . else, switch • Looping while, for, do . . while • Termination exit( ); causes immediate program termination return; terminates execution of a function break; terminates execution of a loop or switch

  11. Choosing Loop Structures • When choosing loops you should not be taken by personal likes and dislikes • They exist to serve different purposes: • for loops should be used when the number of interactions is known and constant • In C++ we have a choice of 2 kinds of indefinite loops • while should be used if the body of the loop may not be executed at all • do – while should be used when the body has to be executed at least once • for loops in C++ can be used for undefined cases but it may make your code obscure • break inside loops should avoided. However you may encounter situations where it does make the code clearer

  12. Functional Abstraction • A powerful mechanism for expressing control abstraction • A function can be used as a tool for abstraction because its behavior (what it does) can be seperated from its implementation (how it does it). • Using the technique of functional decomposition a complex problem can be be decomposed into ever smaller subproblems each expressed as a function call.

  13. Functions • Software systems can contain millions of lines of code • A monolithic program would be difficult to understand, validate, and maintain • Waste resources since no library functions are used • All major applications organize information in modular fashion • Functions implement modular design

  14. Functions • Typically perform a specific task • Can call other functions, themselves • Similar functions are grouped into libraries • Standard libraries complement C++ • stdlib, math Functions must be defined before they are used (called), like variables Standard library functions are declared in a header file

  15. Functional Abstraction • A function is a named subprogram that performs a specific task when it is called. • The function’s specification is a description of what the function does. • Functions use a parameter list for data flow from the caller to the function and from the function to the caller.

  16. Parts of Function Definition type of value returned parameter list name of function int Cube ( int n ) heading { return n * n * n ;body }

  17. Function Definition • Define function header and function body • Value-returning functions return-data-type function-name(parameter list) { constant declarations variable declarations other C++ statements return value }

  18. Function Definition (cont.) • Non value-returning functions void function-name(parameter list) { constant declarations variable declarations other C++ statements }

  19. Parameters classified by location Actual Parameters Formal Parameters Always appear in a function call within the calling block. Always appear in the function heading, or function prototype.

  20. Function Definition (cont.) • The argument names in the function header are referred to as formal parameters. int FindMax(int x, int y) { int maximum; if(x>=y) maximum = x; else maximum = y; return maximum; }

  21. Function Prototype • Every function should have a function prototype. • The function prototype specifies the type of the value that the function returns (if any) and the type, number, and order of the function's arguments. return-data-type function-name(argument data types); or void function-name(argument data types);

  22. Function Prototype (cont.) • The use of function prototypes permits error checking of data types by the compiler. • It also ensures conversion of all arguments passed to the function to the declared argument data type when the function is called.

  23. What is a prototype? A prototype looks like a heading but must end with a semicolon; its parameter list just needs the type of each parameter. int Cube ( int ) ; // prototype

  24. Function naming conventions used • Names of value-returning functions should be nouns (things) or phrases that describe the kind of value (or condition) returned. if (IsSeniorCitizen(thisAge)) discountRate = 0.15; squareFeet = Area(length, width); • Names of non-value-returning functions should be command verbs. PrintHeading(numStars);

  25. Calling a function • A function is called by specifying its name followed by its arguments. • Non-value returning functions:  function-name (data passed to function); • Value returning functions:  results = function-name (data passed to function);

  26. Calling a function (cont.) #include <iostream.h> int FindMax(int, int); // function prototype int main() { int firstnum, secnum, max; cout << "\nEnter two numbers: "; cin >> firstnum >> secnum; max=FindMax(firstnum, secnum); // the function is called here cout << "The maximum is " << max << endl; return 0; } • The argument names in the function call are referred to as actual parameters

  27. Calling a function by value • The function receives a copy of the actual parameter values. • The function cannot change the values of the actual parameters.

  28. Calling a function by reference • Very useful when we need a function which "returns more than one value". • The formal parameter becomes an alias for the actual parameter. • The function can change the values of the actual parameters.

  29. Calling a function by reference (cont.) #include <iostream.h> void newval(float&, float&); // function prototype int main() { float firstnum, secnum; cout << "Enter two numbers: "; cin >> firstnum >> secnum; newval(firstnum, secnum); cout << firstnum << secnum << endl; return 0; } void newval(float& xnum, float& ynum) { xnum = 89.5; ynum = 99.5; }

  30. The "const" modifier • Call by reference is the preferred way to pass a large structure or class instances to functions, since the entire structure need not be copied each time it is used!! • C++ provides us with protection against accidentally changing the values of variables passed by reference with the const operator function prototype: int FindMax(const int&, const int&); function header: int FindMax(const int& x, const int& y);

  31. Parameters • Default Behavior of simple types like int, char, float, double are always value parameters, unless you do something to change that. • To get a reference parameter you need to place & after the type in the function heading and prototype.

  32. When to use reference parameters? • Reference parameters should be used when you want your function to give a value to, or change the value of, a variable from the calling block without an assignment statement in the calling block.

  33. 4000 25 Age CALLING BLOCK MEMORY If you pass only a copy of 25 to a function, it is called “pass-by-value”and the function will not be able to change the contents of Age. It is still 25 when you return.

  34. 4000 25 Age CALLING BLOCK MEMORY BUT, if you pass 4000, the address of Age to a function, it is called “pass-by-reference”and the function will be able to change the contents of Age. It could be 23 or 90 when you return.

  35. 4000 25 Age The value (25) of the actual parameter is passed to the function when it is called. The memory address (4000) of the actual parameter is passed to the function when it is called. CALLING BLOCK MEMORY Value Parameter Reference Parameter

  36. Pass-by-reference is also called . . . • Pass-by-address, or • Pass-by-location.

  37. Pass-by-value “incoming” value of actual parameter CALLING BLOCK FUNCTION CALLED

  38. Pass-by-reference actual parameter has no value yet when call occurs CALLING BLOCK FUNCTION CALLED “outgoing” new value of actual parameter

  39. “incoming” original value of actual parameter Pass-by-reference CALLING BLOCK FUNCTION CALLED “outgoing” changed value of actual parameter

  40. /* in */one-way flow of data into the function /* out */ one-way flow of data out of the function /* inout */ two-way flow into and out of the function Parameters classified by purpose Parameter Data Flow

  41. /* in */ value /* out */ reference & after the type /* inout */ reference & after the type For all data types EXCEPT arrays-- Data Flow Pass by Formal Parameter Needs

  42. /* in */ reference const before the type /* out */ reference /* inout */ reference For arrays-- Data Flow Pass by Formal Parameter Uses

  43. Abstraction Techniques • Functional Abstraction • Top-down design • Data Abstraction (Central Theme of this course)

  44. Functional Decomposition • Probably the most powerful abstraction mechanism • A large task is decomposed (divided) into smaller (complete) tasks which are implemented as functions (or methods) • The programmer can than use these functions, make assumptions about their behaviour without worrying about implementation details • Increases software reuse • Improves software reliability as components can be tested independently and thoroughly • The function specification is what the programmer needs to know

  45. Functional Decomposition • Functions can return value or not (sometimes called procedures) • When designing functions we have to pay attention to data flow • One way flow into the function • One way flow out of the function • Two way flow into and out of the function

  46. Flow into the Function • The caller passes some data to the function but does not expect the function to modify the actual data. • In this case parameters should be passed byvalue // exp must be a positive number int power(int base, int exp) { int power = 1; for (int i=0; i<exp; i++) { power = power * base; } return power }

  47. Flow out of the Function • The caller passes the location of the data as parameter (pass by reference) • The functions modifies the value stored in the location without considering the value currently stored // initialize variables void initialize(float& a, float& b) { a = 1000; b = 100; }

  48. Two-way flow into and from the Function • The caller is passing the location of the date (address) as a parameter (pass by reference) • The function inspect the value currently stored in the location and will possibly modify it. // initialize variables void update(float& a, float& b) { a = a + 1000; b = b + 100; }

  49. Recall: Software Design: Standard Functions Problem Specification: Write a program to compute the real roots of a quadratic equation Problem Analysis: We need the three coefficients of a quadratic equation Using these coefficients we need to determine if the roots will be real or not Determine the value of the roots

  50. Software Design: Standard Functions Data Requirements: Problem Input a (double) - square term coefficient b (double) - linear term coefficient c (double) - constant term Problem Output equation and roots if real equation and message otherwise Recall, the roots of a quadratic equation are given as:

More Related