COP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen
|
|
- Victor Chambers
- 6 years ago
- Views:
Transcription
1 COP4020 Programmig Laguages Subrouties ad Parameter Passig Prof. Robert va Egele
2 Overview Parameter passig modes Subroutie closures as parameters Special-purpose parameters Fuctio returs COP4020 Fall
3 Parameters First some defiitios Formal parameters Lisp: (lambda (a b) (/ (+ a b))) C fuctio: float ave(float a, float b) { retur (a+b)/2.0; } Versus actual parameters Lisp fuctio argumets: (ave x 10.0) C fuctio argumets: ave(x, 10.0) Versus operads (of operators ad special forms) Lisp special forms: (if flag yes o ) C operators: x > 0 && flag Operad hadlig ofte depeds o the type of built-i operator, e.g. special forms ad operators with short-circuit evaluatio COP4020 Fall
4 Parameter Passig Parameter passig modes I I/out Out Parameter passig mechaisms Call by value (i) Call by referece (i+out) Call by result (out) Call by value/result (i+out) Call by ame (i+out) Differet mechaisms used by C, Fortra, Pascal, C++, Java, Ada (ad Algol 60) COP4020 Fall
5 Parameter Passig i C Call by value parameter passig oly Actual parameter is evaluated ad its value assiged to the formal parameter A formal parameter i the fuctio body behaves as a local variable For example: it fac(it ) { if ( < 0) = 0; retur? *fac(-1) : 1; } Passig poiters allows the values of actuals to be modified For example: swap(it *a, it *b) { it t = *a; *a = *b; *b = t; } A fuctio call should explicitly pass poiters, e.g. swap(&x, &y); Arrays ad poiters are exchageable i C A array is automatically passed as a poiter to the array COP4020 Fall
6 Parameter Passig i Fortra Call by referece parameter passig oly If the actual parameter is a l-value (e.g. a variable) its referece is passed to the subroutie If the actual parameter is a r-value (e.g. the value of a expressio) it is assiged to a hidde temporary variable whose referece is passed to the subroutie For example SUBROUTINE SHIFT(A, B, C) INTEGER A, B, C A = B B = C END For example, SHIFT(X, Y, 0) assigs Y to X, ad Y is set to 0 For example, SHIFT(X, 2, 3) assigs 2 to X ad the assigmet to B i the subroutie has o effect, but i Fortra IV this was ot hadled correctly! COP4020 Fall
7 Parameter Passig i Pascal Call by value ad call by referece parameter passig Call by value is similar to C Call by referece: idicated with var qualifier i argumet list For example procedure swap(var a:iteger, var b:iteger) var t; begi t := a; a := b; b := t ed where the var parameters a ad b are passed by referece Programs ca suffer from uecessary data duplicatio overhead Whe a big array is passed by value the etire array is copied! Passig large arrays by referece avoids copy overhead But o clear distictio betwee i-mode or i/out-mode ay loger COP4020 Fall
8 Parameter Passig i C++ Call by value ad call by referece parameter passig Call by value is similar to C Call by referece: use referece (&) operator For example: swap(it &a, it &b) { it t = a; a = b; b = t; } where the referece parameters a ad b are passed by referece Arrays are automatically passed by referece (like i C) Big objects should be passed by referece istead of by value To protect data from modificatio whe passed by referece, use cost, i.e. make it a i-mode parameter For example: store_record_i_file(cost huge_record &r) {... } Compiler will prohibit modificatios of object cost parameters (e.g. poiters) are also supported i ANSI C COP4020 Fall
9 Parameter Passig by Sharig Call by sharig: parameter passig of variables i the referece model Referece model: variables are refereces to (shared) values Smalltalk, Lisp, ML, Clu, ad Java (partly) adopt the referece model of variables The value of the variable is passed as actual argumet, which i fact is a poiter to the (shared) value Essetially this is pass by value of the variable! Java uses both pass by value ad pass by sharig Variables of primitive built-i types are passed by value Class istaces are passed by sharig COP4020 Fall
10 Parameter Passig i Ada I-mode parameters ca be read but ot writte i the subroutie Call by value Out-mode parameters ca be writte but ot read i the subroutie (Ada 95 allows read) Call by result, which uses a local variable to which the writes are made The resultig value is copied to the actual parameter to pass the value out whe the subroutie returs I-out-mode parameters ca be read ad writte i the subroutie Call by value/result uses a local variable that is iitialized by assigig the actual parameter's value to it The resultig value is copied to the actual parameter to pass the value out whe the subroutie returs Call by value, call by result, ad call by value/result parameter passig implemets i, out, ad i/out parameters, respectively Dager ahead: may use call by referece implemetatio for passig oscalars i/out (e.g. records ad arrays) to avoid copyig large objects! COP4020 Fall
11 Parameter Passig i Ada: Example For example procedure shift(a:out iteger, b:i out iteger, c:i iteger) is begi a := b; b := c; ed shift; Here, a is passed out, b is passed i ad out, ad c is passed i COP4020 Fall
12 Parameter Passig i Ada (cot d) The Ada compiler geerates specific code for the example shift procedure for i, out, ad i/out parameters to implemet call by value (i), call by result (out), ad call by value/result (i/out), which is similar to the followig C fuctio: void shift(it *a, it *b, it c) { it tmpa, tmpb = *b, tmpc = c; // copy iput values at begi } tmpa = tmpb; tmpb = tmpc; // perform operatios o temps *a = tmpa; *b = tmpb; // copy result values out before retur Temps are iitialized, operated o, ad copied to out mode parameters This is more efficiet tha pass by referece, because it avoids repeated poiter idirectio to access parameter values The Ada compiler may decide to use call by referece for passig oscalars (e.g. records ad arrays) for memory access optimizatio Okay for i-mode, because the parameter may ot be writte Okay for out ad i-out modes, sice the parameter is writte ayway COP4020 Fall
13 Parameter Passig ad Aliasig A alias is a variable or formal parameter that refers to the same value as aother variable or formal parameter Example variable aliases i C++: it i, &j = i; // j refers to i (is a alias for i) i = 2; j = 3; cout << i; // prits 3 Example parameter aliases i C++: shift(it &a, it &b, cost it &c) { a = b; b = c; } The result of shift(x, y, x) is that x is set to y but y is uchaged Example mixig of variable ad parameter aliases i C++: it sum = 0; score(it &total, it val) { sum += val; total += val; } The result of score(sum, 7) is that sum is icremeted by 14 COP4020 Fall
14 Parameter Passig ad Aliasig (cot d) Java adopts referece model of variables ad call by sharig Watch out for aliases, sice i referece model all assigmets create aliases Ada forbids parameter aliases Allows compiler to choose call by referece with the same effect as call by result But most compilers do t check ad the resultig program behavior is udefied COP4020 Fall
15 Parameter Passig i Algol 60 Call by ame parameter passig by default, also call by value Passes actual argumets such as expressios ito the subroutie body for (re)evaluatio (reevaluatio doe via code thuks ) Jese's device utilizes call by ame: real procedure sum(expr, i, low, high); value low, high; low ad high are passed by value real expr; expr ad i are passed by ame iteger i, low, high; begi real rt; rt := 0; for i := low step 1 util high do rt := rt + expr; sum := rt ed sum the value of expr depeds o the value of i retur value by assigig to fuctio ame y := sum(3*x*x-5*x+2, x, 1, 10) calculates 10 y = Σ 3x 2-5x+2 x=1 COP4020 Fall
16 Macro Expasio C/C++ macros (also called defies) adopt a form of call by ame For example #defie max(a,b) ( (a)>(b)? (a) : (b) ) Macro expasio is applied to the program source text ad amouts to the substitutio of the formal parameters with the actual parameters i the macro For example max(+1, m) is replaced by ((+1)>(m)?(+1):(m)) Note: formal parameters are ofte parethesized to avoid sytax problems whe expadig Similar to call by ame, actual parameters are re-evaluated each time the formal parameter is used Watch out for re-evaluatio of fuctio calls i actual parameters, for example max(somefuc(),0) results i the evaluatio of somefuc() twice if it returs a value >0 COP4020 Fall
17 Parameter Passig Issues Call by ame problem: hard to write a swap routie that works: procedure swap(a, b) iteger a, b, t; begi t := a; a := b; b := t ed swap Cosider swap(i, a[i]), which executes: t := i i := a[i] this chages i a[i] := t assigs t to wrog array elemet COP4020 Fall
18 Parameter Passig Issue (cot d) Call by value/result problem: behaves differetly compared to call by referece i the presece of aliases (that s why Ada forbids it) For example: procedure shift(a:out iteger, b:i out iteger, c:i iteger) is begi a := b; b := c; ed shift; Whe shift(x,x,0) is called by referece the resultig value of x is 0 Whe shift(x,x,0) is called by value/result the resultig value of x is either uchaged or 0 (because the order of copyig out mode parameters is uspecified) COP4020 Fall
19 Coformat Arrays Some laguages support coformat arrays (or ope arrays) Examples: Ada, Stadard Pascal, Modula-2 Pascal arrays are types with embedded costat array bouds Arrays have fixed shape ad size Problem whe for example sortig arrays of differet sizes because sort procedure accepts oe type of array with oe size oly Array parameters i Stadard Pascal are coformat ad array size is ot fixed at compile-time For example: fuctio sum(a : array[low..high : iteger] of real) : real... Fuctio sum accepts real typed arrays ad low ad high act like formal parameters that are set to the lower ad upper boud idex of the actual array parameter C passes oly poiters to arrays to fuctios ad array size has to be determied usig some other meas (e.g. as aother parameter) COP4020 Fall
20 Closures as Parameters Recall that a subroutie closure is a referece to a subroutie together with its referecig eviromet Stadard Pascal, Ada 95, Modula-2+3 fully support passig of subrouties as closures Stadard Pascal example: procedure apply_to_a(fuctio f(:iteger) : iteger; var A : array [low..high : iteger] of iteger); var i : iteger; begi for i := low to high do A[i] := f(a[i]) ed C/C++ supports fuctio poiters ad lambdas (C++11) Lambdas ca capture a referece eviromet Fuctio poiters are simplistic, for example: void apply_to_a(it (*f)(it), it A[], it A_size) { it i; for (i = 0; i < A_size; i++) A[i] = f(a[i]); } COP4020 Fall
21 Default Parameters Ada, C++, Commo Lisp, ad Fortra 90 support default parameters A default parameter is a formal parameter with a default value Whe the actual parameter value is omitted i a subroutie call, the user-specified default value is used Example i C++: void prit_um(it, it base = 10)... A call to prit_um(35) uses default value 10 for base as if prit_um(35,10) was called Example i Ada: procedure put(item : i iteger; width : i field := default_width; base : i umber_base := 10) is... A call to put(35) uses default values for the width ad base parameters COP4020 Fall
22 Positioal Versus Named Parameters Positioal parameters: the order of formal ad actual argumets is fixed All programmig laguages adopt this atural covetio Named parameter: (also called keyword parameter) explicitly bids the actual parameter to the formal parameter Ada, Modula-3, Commo Lisp, ad Fortra 90 For example i Ada: put(item => 35, base => 8); this "assigs" 35 to item ad 8 to base, which is the same as: put(base => 8, item => 35); ad we ca mix positioal ad ame parameters as well: put(35, base => 8); Pro: documetatio of parameter purpose Pro: allows default parameters aywhere i formal parameter list, whereas with positioal parameters the use of default parameters is restricted to the last parameter(s) oly, because the compiler caot tell which parameter is optioal i a subroutie ivocatio COP4020 Fall
23 Variable Argumet Lists C,C++, ad Commo Lisp are uusual i that they allow defiig subrouties that take a variable umber of argumets Example i C: #iclude <stdarg.h> it plus(it um,...) { it sum; va_list args; // declare list of argumets va_start(args, um); // iitialize list of argumets for (it i=0; i<um; i++) sum += va_arg(args, it); // get ext argumet (assumed to be it) va_ed(args); // clea up list of argumets retur sum; } Fuctio plus adds a set of itegers, where the umber of itegers is the first parameter to the fuctio: plus(4,3,2,1,4) is 10 Used i the pritf ad scaf text formattig fuctios i C Variable umber of argumets i C ad C++ is ot type safe as parameter types are ot checked I Commo Lisp, oe ca write ( ) to add the itegers COP4020 Fall
24 Fuctio Returs Some programmig laguages allow a fuctio to retur ay type of data structure, except maybe a subroutie (requires first-class subrouties) Modula-3 ad Ada allow a fuctio to retur a subroutie as a closure C ad C++ allow fuctios to retur poiters to fuctios (o closures) Some laguages use special variable to hold fuctio retur value Example i Pascal: fuctio max(a : iteger; b : iteger) : iteger; begi if a>b the max := a else max := b ed There is o retur statemet, istead the fuctio returs with the value of max whe it reaches the ed The subroutie frame reserves a slot for the retur value ayway, so these laguages make the slot explicitly available COP4020 Fall
25 Fuctio Returs (cot d) Ada, C, C++, Java, ad other more moder laguages typically use a explicit retur statemet to retur a value from a fuctio Example i C: it max(it a, it b) { if (a>b) retur a; else retur b; } Programmers may eed a temporary variable for icremetal operatios o the retur value For example: it fac(it ) { it ret = 1; for (i = 2; i <= ; i++) ret *= i; retur ret; } Wastes time copyig the temporary variable value ito retur slot of subroutie frame o the stack COP4020 Fall
COP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen
COP4020 Programming Languages Subroutines and Parameter Passing Prof. Robert van Engelen Overview Parameter passing modes Subroutine closures as parameters Special-purpose parameters Function returns COP4020
More informationChapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 9 Poiters ad Dyamic Arrays Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 9.1 Poiters 9.2 Dyamic Arrays Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-3
More informationCOP4020 Programming Languages. Compilers and Interpreters Prof. Robert van Engelen
COP4020 mig Laguages Compilers ad Iterpreters Prof. Robert va Egele Overview Commo compiler ad iterpreter cofiguratios Virtual machies Itegrated developmet eviromets Compiler phases Lexical aalysis Sytax
More informationCS 11 C track: lecture 1
CS 11 C track: lecture 1 Prelimiaries Need a CMS cluster accout http://acctreq.cms.caltech.edu/cgi-bi/request.cgi Need to kow UNIX IMSS tutorial liked from track home page Track home page: http://courses.cms.caltech.edu/courses/cs11/material
More informationCOP4020 Programming Languages. Functional Programming Prof. Robert van Engelen
COP4020 Programmig Laguages Fuctioal Programmig Prof. Robert va Egele Overview What is fuctioal programmig? Historical origis of fuctioal programmig Fuctioal programmig today Cocepts of fuctioal programmig
More informationChapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 11 Frieds, Overloaded Operators, ad Arrays i Classes Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Overview 11.1 Fried Fuctios 11.2 Overloadig Operators 11.3 Arrays ad Classes 11.4
More informationPython Programming: An Introduction to Computer Science
Pytho Programmig: A Itroductio to Computer Sciece Chapter 6 Defiig Fuctios Pytho Programmig, 2/e 1 Objectives To uderstad why programmers divide programs up ito sets of cooperatig fuctios. To be able to
More informationCMPT 125 Assignment 2 Solutions
CMPT 25 Assigmet 2 Solutios Questio (20 marks total) a) Let s cosider a iteger array of size 0. (0 marks, each part is 2 marks) it a[0]; I. How would you assig a poiter, called pa, to store the address
More informationPseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance
Aalysis of Algorithms Iput Algorithm Output A algorithm is a step-by-step procedure for solvig a problem i a fiite amout of time. Pseudocode ( 1.1) High-level descriptio of a algorithm More structured
More informationRunning Time. Analysis of Algorithms. Experimental Studies. Limitations of Experiments
Ruig Time Aalysis of Algorithms Iput Algorithm Output A algorithm is a step-by-step procedure for solvig a problem i a fiite amout of time. Most algorithms trasform iput objects ito output objects. The
More informationRunning Time ( 3.1) Analysis of Algorithms. Experimental Studies. Limitations of Experiments
Ruig Time ( 3.1) Aalysis of Algorithms Iput Algorithm Output A algorithm is a step- by- step procedure for solvig a problem i a fiite amout of time. Most algorithms trasform iput objects ito output objects.
More informationAnalysis of Algorithms
Aalysis of Algorithms Iput Algorithm Output A algorithm is a step-by-step procedure for solvig a problem i a fiite amout of time. Ruig Time Most algorithms trasform iput objects ito output objects. The
More informationWhat are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs
What are we goig to lear? CSC316-003 Data Structures Aalysis of Algorithms Computer Sciece North Carolia State Uiversity Need to say that some algorithms are better tha others Criteria for evaluatio Structure
More informationOutline and Reading. Analysis of Algorithms. Running Time. Experimental Studies. Limitations of Experiments. Theoretical Analysis
Outlie ad Readig Aalysis of Algorithms Iput Algorithm Output Ruig time ( 3.) Pseudo-code ( 3.2) Coutig primitive operatios ( 3.3-3.) Asymptotic otatio ( 3.6) Asymptotic aalysis ( 3.7) Case study Aalysis
More informationClasses and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1
Classes ad Objects jvo@ualg.pt José Valete de Oliveira 4-1 Agai: Distace betwee poits withi the first quadrat Sample iput Sample output 1 1 3 4 2 jvo@ualg.pt José Valete de Oliveira 4-2 1 The simplest
More informationChapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 5 Fuctios for All Subtasks Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 5.1 void Fuctios 5.2 Call-By-Referece Parameters 5.3 Usig Procedural Abstractio 5.4 Testig ad Debuggig
More informationData Structures and Algorithms. Analysis of Algorithms
Data Structures ad Algorithms Aalysis of Algorithms Outlie Ruig time Pseudo-code Big-oh otatio Big-theta otatio Big-omega otatio Asymptotic algorithm aalysis Aalysis of Algorithms Iput Algorithm Output
More informationLast class. n Scheme. n Equality testing. n eq? vs. equal? n Higher-order functions. n map, foldr, foldl. n Tail recursion
Aoucemets HW6 due today HW7 is out A team assigmet Submitty page will be up toight Fuctioal correctess: 75%, Commets : 25% Last class Equality testig eq? vs. equal? Higher-order fuctios map, foldr, foldl
More informationAnalysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis
Itro to Algorithm Aalysis Aalysis Metrics Slides. Table of Cotets. Aalysis Metrics 3. Exact Aalysis Rules 4. Simple Summatio 5. Summatio Formulas 6. Order of Magitude 7. Big-O otatio 8. Big-O Theorems
More informationAnalysis of Algorithms
Aalysis of Algorithms Ruig Time of a algorithm Ruig Time Upper Bouds Lower Bouds Examples Mathematical facts Iput Algorithm Output A algorithm is a step-by-step procedure for solvig a problem i a fiite
More informationLinked Lists 11/16/18. Preliminaries. Java References. Objects and references. Self references. Linking self-referential nodes
Prelimiaries Liked Lists public class StrageObject { Strig ame; StrageObject other; Arrays are ot always the optimal data structure: A array has fixed size eeds to be copied to expad its capacity Addig
More informationChapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 10 Defiig Classes Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 10.1 Structures 10.2 Classes 10.3 Abstract Data Types 10.4 Itroductio to Iheritace Copyright 2015 Pearso Educatio,
More informationHigh-Order Language APPLICATION LEVEL HIGH-ORDER LANGUAGE LEVEL ASSEMBLY LEVEL OPERATING SYSTEM LEVEL INSTRUCTION SET ARCHITECTURE LEVEL
Chapter 2 C High-Order Laguage APPLICATION LEVEL HIGH-ORDER LANGUAGE LEVEL 6 ASSEMBLY LEVEL OPERATING SYSTEM LEVEL INSTRUCTION SET ARCHITECTURE LEVEL MICROCODE LEVEL LOGIC GATE LEVEL Figure 2. 7 6 5 4
More informationCIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19
CIS Data Structures ad Algorithms with Java Sprig 09 Stacks, Queues, ad Heaps Moday, February 8 / Tuesday, February 9 Stacks ad Queues Recall the stack ad queue ADTs (abstract data types from lecture.
More informationFrom last week. Lecture 5. Outline. Principles of programming languages
Priciples of programmig laguages From last week Lecture 5 http://few.vu.l/~silvis/ppl/2007 Natalia Silvis-Cividjia e-mail: silvis@few.vu.l ML has o assigmet. Explai how to access a old bidig? Is & for
More informationComputers and Scientific Thinking
Computers ad Scietific Thikig David Reed, Creighto Uiversity Chapter 15 JavaScript Strigs 1 Strigs as Objects so far, your iteractive Web pages have maipulated strigs i simple ways use text box to iput
More informationHow do we evaluate algorithms?
F2 Readig referece: chapter 2 + slides Algorithm complexity Big O ad big Ω To calculate ruig time Aalysis of recursive Algorithms Next time: Litterature: slides mostly The first Algorithm desig methods:
More informationA graphical view of big-o notation. c*g(n) f(n) f(n) = O(g(n))
ca see that time required to search/sort grows with size of We How do space/time eeds of program grow with iput size? iput. time: cout umber of operatios as fuctio of iput Executio size operatio Assigmet:
More informationBasic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.
5-23 The course that gives CM its Zip Memory Maagemet II: Dyamic Storage Allocatio Mar 6, 2000 Topics Segregated lists Buddy system Garbage collectio Mark ad Sweep Copyig eferece coutig Basic allocator
More informationCOP4020 Programming Languages. Names, Scopes, and Bindings Prof. Robert van Engelen
COP4020 Programmig Laguages Names, Scopes, ad Bidigs Prof. Robert va Egele Overview Abstractios ad ames Bidig time Object lifetime Object storage maagemet Static allocatio Stack allocatio Heap allocatio
More informationChapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 8 Strigs ad Vectors Overview 8.1 A Array Type for Strigs 8.2 The Stadard strig Class 8.3 Vectors Slide 8-3 8.1 A Array Type for Strigs A Array Type for Strigs C-strigs ca be used to represet strigs
More informationProgramming with Shared Memory PART II. HPC Spring 2017 Prof. Robert van Engelen
Programmig with Shared Memory PART II HPC Sprig 2017 Prof. Robert va Egele Overview Sequetial cosistecy Parallel programmig costructs Depedece aalysis OpeMP Autoparallelizatio Further readig HPC Sprig
More informationRecursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames
Uit 4, Part 3 Recursio Computer Sciece S-111 Harvard Uiversity David G. Sulliva, Ph.D. Review: Method Frames Whe you make a method call, the Java rutime sets aside a block of memory kow as the frame of
More informationChapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 8 Strigs ad Vectors Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 8.1 A Array Type for Strigs 8.2 The Stadard strig Class 8.3 Vectors Copyright 2015 Pearso Educatio, Ltd..
More informationAbstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:
Chapter 4 Computatio Bjare Stroustrup www.stroustrup.com/programmig Abstract Today, I ll preset the basics of computatio. I particular, we ll discuss expressios, how to iterate over a series of values
More informationChapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 4 Procedural Abstractio ad Fuctios That Retur a Value Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 4.1 Top-Dow Desig 4.2 Predefied Fuctios 4.3 Programmer-Defied Fuctios 4.4
More informationBehavioral Modeling in Verilog
Behavioral Modelig i Verilog COE 202 Digital Logic Desig Dr. Muhamed Mudawar Kig Fahd Uiversity of Petroleum ad Mierals Presetatio Outlie Itroductio to Dataflow ad Behavioral Modelig Verilog Operators
More informationLecture 1: Introduction and Strassen s Algorithm
5-750: Graduate Algorithms Jauary 7, 08 Lecture : Itroductio ad Strasse s Algorithm Lecturer: Gary Miller Scribe: Robert Parker Itroductio Machie models I this class, we will primarily use the Radom Access
More informationimplement language system
Outlie Priciples of programmig laguages Lecture 3 http://few.vu.l/~silvis/ppl/2007 Part I. Laguage systems Part II. Fuctioal programmig. First look at ML. Natalia Silvis-Cividjia e-mail: silvis@few.vu.l
More informationHomework 1 Solutions MA 522 Fall 2017
Homework 1 Solutios MA 5 Fall 017 1. Cosider the searchig problem: Iput A sequece of umbers A = [a 1,..., a ] ad a value v. Output A idex i such that v = A[i] or the special value NIL if v does ot appear
More informationCIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13
CIS Data Structures ad Algorithms with Java Sprig 08 Stacks ad Queues Moday, February / Tuesday, February Learig Goals Durig this lab, you will: Review stacks ad queues. Lear amortized ruig time aalysis
More informationPython Programming: An Introduction to Computer Science
Pytho Programmig: A Itroductio to Computer Sciece Chapter 1 Computers ad Programs 1 Objectives To uderstad the respective roles of hardware ad software i a computig system. To lear what computer scietists
More informationCMSC Computer Architecture Lecture 12: Virtual Memory. Prof. Yanjing Li University of Chicago
CMSC 22200 Computer Architecture Lecture 12: Virtual Memory Prof. Yajig Li Uiversity of Chicago A System with Physical Memory Oly Examples: most Cray machies early PCs Memory early all embedded systems
More informationOverview. Chapter 18 Vectors and Arrays. Reminder. vector. Bjarne Stroustrup
Chapter 18 Vectors ad Arrays Bjare Stroustrup Vector revisited How are they implemeted? Poiters ad free store Destructors Iitializatio Copy ad move Arrays Array ad poiter problems Chagig size Templates
More informationn Haskell n Syntax n Lazy evaluation n Static typing and type inference n Algebraic data types n Pattern matching n Type classes
Aoucemets Quiz 7 HW 9 is due o Friday Raibow grades HW 1-6 plus 8. Please, read our commets o 8! Exam 1-2 Quiz 1-6 Ay questios/cocers, let us kow ASAP Last Class Haskell Sytax Lazy evaluatio Static typig
More informationToday s objectives. CSE401: Introduction to Compiler Construction. What is a compiler? Administrative Details. Why study compilers?
CSE401: Itroductio to Compiler Costructio Larry Ruzzo Sprig 2004 Today s objectives Admiistrative details Defie compilers ad why we study them Defie the high-level structure of compilers Associate specific
More informationLast Class. Announcements. Lecture Outline. Types. Structural Equivalence. Type Equivalence. Read: Scott, Chapters 7 and 8. T2 y; x = y; n Types
Aoucemets HW9 due today HW10 comig up, will post after class Team assigmet Data abstractio (types) ad cotrol abstractio (parameter passig) Due o Tuesday, November 27 th Last Class Types Type systems Type
More informationn Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis
Overview Chapter 6 Writig a Program Bjare Stroustrup Some thoughts o software developmet The idea of a calculator Usig a grammar Expressio evaluatio Program orgaizatio www.stroustrup.com/programmig 3 Buildig
More informationLecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming
Lecture Notes 6 Itroductio to algorithm aalysis CSS 501 Data Structures ad Object-Orieted Programmig Readig for this lecture: Carrao, Chapter 10 To be covered i this lecture: Itroductio to algorithm aalysis
More informationCOSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1
COSC 1P03 Ch 7 Recursio Itroductio to Data Structures 8.1 COSC 1P03 Recursio Recursio I Mathematics factorial Fiboacci umbers defie ifiite set with fiite defiitio I Computer Sciece sytax rules fiite defiitio,
More information. Written in factored form it is easy to see that the roots are 2, 2, i,
CMPS A Itroductio to Programmig Programmig Assigmet 4 I this assigmet you will write a java program that determies the real roots of a polyomial that lie withi a specified rage. Recall that the roots (or
More informationCode Review Defects. Authors: Mika V. Mäntylä and Casper Lassenius Original version: 4 Sep, 2007 Made available online: 24 April, 2013
Code Review s Authors: Mika V. Mätylä ad Casper Lasseius Origial versio: 4 Sep, 2007 Made available olie: 24 April, 2013 This documet cotais further details of the code review defects preseted i [1]. of
More informationExamples and Applications of Binary Search
Toy Gog ITEE Uiersity of Queeslad I the secod lecture last week we studied the biary search algorithm that soles the problem of determiig if a particular alue appears i a sorted list of iteger or ot. We
More informationMajor CSL Write your name and entry no on every sheet of the answer script. Time 2 Hrs Max Marks 70
NOTE:. Attempt all seve questios. Major CSL 02 2. Write your ame ad etry o o every sheet of the aswer script. Time 2 Hrs Max Marks 70 Q No Q Q 2 Q 3 Q 4 Q 5 Q 6 Q 7 Total MM 6 2 4 0 8 4 6 70 Q. Write a
More informationn Maurice Wilkes, 1949 n Organize software to minimize errors. n Eliminate most of the errors we made anyway.
Bjare Stroustrup www.stroustrup.com/programmig Chapter 5 Errors Abstract Whe we program, we have to deal with errors. Our most basic aim is correctess, but we must deal with icomplete problem specificatios,
More informationAnalysis of Algorithms
Presetatio for use with the textbook, Algorithm Desig ad Applicatios, by M. T. Goodrich ad R. Tamassia, Wiley, 2015 Aalysis of Algorithms Iput 2015 Goodrich ad Tamassia Algorithm Aalysis of Algorithms
More informationHash Tables. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015.
Presetatio for use with the textbook Algorithm Desig ad Applicatios, by M. T. Goodrich ad R. Tamassia, Wiley, 2015 Hash Tables xkcd. http://xkcd.com/221/. Radom Number. Used with permissio uder Creative
More informationCSC 220: Computer Organization Unit 11 Basic Computer Organization and Design
College of Computer ad Iformatio Scieces Departmet of Computer Sciece CSC 220: Computer Orgaizatio Uit 11 Basic Computer Orgaizatio ad Desig 1 For the rest of the semester, we ll focus o computer architecture:
More informationwhy study sorting? Sorting is a classic subject in computer science. There are three reasons for studying sorting algorithms.
Chapter 5 Sortig IST311 - CIS65/506 Clevelad State Uiversity Prof. Victor Matos Adapted from: Itroductio to Java Programmig: Comprehesive Versio, Eighth Editio by Y. Daiel Liag why study sortig? Sortig
More informationCSE 2320 Notes 8: Sorting. (Last updated 10/3/18 7:16 PM) Idea: Take an unsorted (sub)array and partition into two subarrays such that.
CSE Notes 8: Sortig (Last updated //8 7:6 PM) CLRS 7.-7., 9., 8.-8. 8.A. QUICKSORT Cocepts Idea: Take a usorted (sub)array ad partitio ito two subarrays such that p q r x y z x y y z Pivot Customarily,
More informationCS 111: Program Design I Lecture 16: Module Review, Encodings, Lists
CS 111: Program Desig I Lecture 16: Module Review, Ecodigs, Lists Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago October 18, 2016 Last time Dot otatio ad methods Padas: user maual poit
More informationCS200: Hash Tables. Prichard Ch CS200 - Hash Tables 1
CS200: Hash Tables Prichard Ch. 13.2 CS200 - Hash Tables 1 Table Implemetatios: average cases Search Add Remove Sorted array-based Usorted array-based Balaced Search Trees O(log ) O() O() O() O(1) O()
More informationUNIT 4C Iteration: Scalability & Big O. Efficiency
UNIT 4C Iteratio: Scalability & Big O 1 Efficiecy A computer program should be totally correct, but it should also execute as quickly as possible (time-efficiecy) use memory wisely (storage-efficiecy)
More informationn The C++ template facility provides the ability to define n A generic facility allows code to be written once then
UCLA PIC 10 B Problem Solvig usig C++ Programmig Ivo Diov, Asst. Prof. i Mathematics, Neurology, Statistics Istructor: Teachig Assistat: Suzae Nezzar, Mathematics Chapter 13 Templates for More Abstractio
More information10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output
File class i Java File Iput ad Output TOPICS File Iput Exceptio Hadlig File Output Programmers refer to iput/output as "I/O". The File class represets files as objects. The class is defied i the java.io
More informationCS 111: Program Design I Lecture 15: Objects, Pandas, Modules. Robert H. Sloan & Richard Warner University of Illinois at Chicago October 13, 2016
CS 111: Program Desig I Lecture 15: Objects, Padas, Modules Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago October 13, 2016 OBJECTS AND DOT NOTATION Objects (Implicit i Chapter 2, Variables,
More informationPackage RcppRoll. December 22, 2014
Type Package Package RcppRoll December 22, 2014 Title Fast rollig fuctios through Rcpp ad RcppArmadillo Versio 0.1.0 Date 2013-01-10 Author Kevi Ushey Maitaier Kevi Ushey RcppRoll
More informationRecursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:
Recursio Recursio Jordi Cortadella Departmet of Computer Sciece Priciple: Reduce a complex problem ito a simpler istace of the same problem Recursio Itroductio to Programmig Dept. CS, UPC 2 Mathematical
More informationCopyright 2016 Ramez Elmasri and Shamkant B. Navathe
Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe CHAPTER 18 Strategies for Query Processig Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe Itroductio DBMS techiques to process a query Scaer idetifies
More informationSolutions to Final COMS W4115 Programming Languages and Translators Monday, May 4, :10-5:25pm, 309 Havemeyer
Departmet of Computer ciece Columbia Uiversity olutios to Fial COM W45 Programmig Laguages ad Traslators Moday, May 4, 2009 4:0-5:25pm, 309 Havemeyer Closed book, o aids. Do questios 5. Each questio is
More informationChapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 6 I/O Streams as a Itroductio to Objects ad Classes Overview 6.1 Streams ad Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Slide 6-3 6.1 Streams ad Basic File I/O I/O Streams I/O refers
More informationSolution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:
CS 604 Data Structures Midterm Sprig, 00 VIRG INIA POLYTECHNIC INSTITUTE AND STATE U T PROSI M UNI VERSI TY Istructios: Prit your ame i the space provided below. This examiatio is closed book ad closed
More informationChapter 3. More Flow of Control. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 3 More Flow of Cotrol Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 3.1 Usig Boolea Expressios 3.2 Multiway Braches 3.3 More about C++ Loop Statemets 3.4 Desigig Loops Copyright
More informationUniversity of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures
Uiversity of Waterloo Departmet of Electrical ad Computer Egieerig ECE 250 Algorithms ad Data Structures Midterm Examiatio ( pages) Istructor: Douglas Harder February 7, 2004 7:30-9:00 Name (last, first)
More informationData Structures Week #9. Sorting
Data Structures Week #9 Sortig Outlie Motivatio Types of Sortig Elemetary (O( 2 )) Sortig Techiques Other (O(*log())) Sortig Techiques 21.Aralık.2010 Boraha Tümer, Ph.D. 2 Sortig 21.Aralık.2010 Boraha
More informationPolynomial Functions and Models. Learning Objectives. Polynomials. P (x) = a n x n + a n 1 x n a 1 x + a 0, a n 0
Polyomial Fuctios ad Models 1 Learig Objectives 1. Idetify polyomial fuctios ad their degree 2. Graph polyomial fuctios usig trasformatios 3. Idetify the real zeros of a polyomial fuctio ad their multiplicity
More informationData diverse software fault tolerance techniques
Data diverse software fault tolerace techiques Complemets desig diversity by compesatig for desig diversity s s limitatios Ivolves obtaiig a related set of poits i the program data space, executig the
More informationChapter 24. Sorting. Objectives. 1. To study and analyze time efficiency of various sorting algorithms
Chapter 4 Sortig 1 Objectives 1. o study ad aalyze time efficiecy of various sortig algorithms 4. 4.7.. o desig, implemet, ad aalyze bubble sort 4.. 3. o desig, implemet, ad aalyze merge sort 4.3. 4. o
More informationCSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)
CSC165H1, Witer 018 Learig Objectives By the ed of this worksheet, you will: Aalyse the ruig time of fuctios cotaiig ested loops. 1. Nested loop variatios. Each of the followig fuctios takes as iput a
More informationtop() Applications of Stacks
CS22 Algorithms ad Data Structures MW :00 am - 2: pm, MSEC 0 Istructor: Xiao Qi Lecture 6: Stacks ad Queues Aoucemets Quiz results Homework 2 is available Due o September 29 th, 2004 www.cs.mt.edu~xqicoursescs22
More informationChapter 2. C++ Basics. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 2 C++ Basics Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 2.1 Variables ad Assigmets 2.2 Iput ad Output 2.3 Data Types ad Expressios 2.4 Simple Flow of Cotrol 2.5 Program
More informationCS 111: Program Design I Lecture # 7: First Loop, Web Crawler, Functions
CS 111: Program Desig I Lecture # 7: First Loop, Web Crawler, Fuctios Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago September 18, 2018 What will this prit? x = 5 if x == 3: prit("hi!")
More informationCSE 417: Algorithms and Computational Complexity
Time CSE 47: Algorithms ad Computatioal Readig assigmet Read Chapter of The ALGORITHM Desig Maual Aalysis & Sortig Autum 00 Paul Beame aalysis Problem size Worst-case complexity: max # steps algorithm
More informationCOMP Parallel Computing. PRAM (1): The PRAM model and complexity measures
COMP 633 - Parallel Computig Lecture 2 August 24, 2017 : The PRAM model ad complexity measures 1 First class summary This course is about parallel computig to achieve high-er performace o idividual problems
More informationCopyright 2016 Ramez Elmasri and Shamkant B. Navathe
Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe CHAPTER 19 Query Optimizatio Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe Itroductio Query optimizatio Coducted by a query optimizer i a DBMS Goal:
More informationCS 111: Program Design I Lecture 15: Modules, Pandas again. Robert H. Sloan & Richard Warner University of Illinois at Chicago March 8, 2018
CS 111: Program Desig I Lecture 15: Modules, Padas agai Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago March 8, 2018 PYTHON STANDARD LIBRARY & BEYOND: MODULES Extedig Pytho Every moder
More informationProject 2.5 Improved Euler Implementation
Project 2.5 Improved Euler Implemetatio Figure 2.5.10 i the text lists TI-85 ad BASIC programs implemetig the improved Euler method to approximate the solutio of the iitial value problem dy dx = x+ y,
More informationCS211 Fall 2003 Prelim 2 Solutions and Grading Guide
CS11 Fall 003 Prelim Solutios ad Gradig Guide Problem 1: (a) obj = obj1; ILLEGAL because type of referece must always be a supertype of type of object (b) obj3 = obj1; ILLEGAL because type of referece
More informationChapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 1 Itroductio to Computers ad C++ Programmig Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 1.1 Computer Systems 1.2 Programmig ad Problem Solvig 1.3 Itroductio to C++ 1.4 Testig
More informationInductive Definition to Recursive Function
PDS: CS 11002 Computer Sc & Egg: IIT Kharagpur 1 Iductive Defiitio to Recursive Fuctio PDS: CS 11002 Computer Sc & Egg: IIT Kharagpur 2 Factorial Fuctio Cosider the followig recursive defiitio of the factorial
More informationLecture 5. Counting Sort / Radix Sort
Lecture 5. Coutig Sort / Radix Sort T. H. Corme, C. E. Leiserso ad R. L. Rivest Itroductio to Algorithms, 3rd Editio, MIT Press, 2009 Sugkyukwa Uiversity Hyuseug Choo choo@skku.edu Copyright 2000-2018
More informationIMP: Superposer Integrated Morphometrics Package Superposition Tool
IMP: Superposer Itegrated Morphometrics Package Superpositio Tool Programmig by: David Lieber ( 03) Caisius College 200 Mai St. Buffalo, NY 4208 Cocept by: H. David Sheets, Dept. of Physics, Caisius College
More informationSorting in Linear Time. Data Structures and Algorithms Andrei Bulatov
Sortig i Liear Time Data Structures ad Algorithms Adrei Bulatov Algorithms Sortig i Liear Time 7-2 Compariso Sorts The oly test that all the algorithms we have cosidered so far is compariso The oly iformatio
More information6.854J / J Advanced Algorithms Fall 2008
MIT OpeCourseWare http://ocw.mit.edu 6.854J / 18.415J Advaced Algorithms Fall 2008 For iformatio about citig these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. 18.415/6.854 Advaced Algorithms
More informationOverview. Common tasks. Observation. Chapter 20 The STL (containers, iterators, and algorithms) 8/13/18. Bjarne Stroustrup
Overview Chapter 20 The STL (cotaiers, iterators, ad algorithms) Bjare Stroustrup www.stroustrup.com/programmig Commo tasks ad ideals Geeric programmig Cotaiers, algorithms, ad iterators The simplest algorithm:
More informationPriority Queues. Binary Heaps
Priority Queues Biary Heaps Priority Queues Priority: some property of a object that allows it to be prioritized with respect to other objects of the same type Mi Priority Queue: homogeeous collectio of
More informationCIS 121. Introduction to Trees
CIS 121 Itroductio to Trees 1 Tree ADT Tree defiitio q A tree is a set of odes which may be empty q If ot empty, the there is a distiguished ode r, called root ad zero or more o-empty subtrees T 1, T 2,
More informationOnes Assignment Method for Solving Traveling Salesman Problem
Joural of mathematics ad computer sciece 0 (0), 58-65 Oes Assigmet Method for Solvig Travelig Salesma Problem Hadi Basirzadeh Departmet of Mathematics, Shahid Chamra Uiversity, Ahvaz, Ira Article history:
More informationDATA STRUCTURES. amortized analysis binomial heaps Fibonacci heaps union-find. Data structures. Appetizer. Appetizer
Data structures DATA STRUCTURES Static problems. Give a iput, produce a output. Ex. Sortig, FFT, edit distace, shortest paths, MST, max-flow,... amortized aalysis biomial heaps Fiboacci heaps uio-fid Dyamic
More informationBig-O Analysis. Asymptotics
Big-O Aalysis 1 Defiitio: Suppose that f() ad g() are oegative fuctios of. The we say that f() is O(g()) provided that there are costats C > 0 ad N > 0 such that for all > N, f() Cg(). Big-O expresses
More information