FALL 2001ICOM 4015 - Lecture 21 ICOM 4015 Advanced Programming Lecture 2 Procedural Abstraction Reading: LNN Chapter 4, 14 Prof. Bienvenido Velez.

Slides:



Advertisements
Similar presentations
Modular Programming With Functions
Advertisements

Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 5. Functions.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
1. 2 FUNCTION INLINE FUNCTION DIFFERENCE BETWEEN FUNCTION AND INLINE FUNCTION CONCLUSION 3.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Chapter 6: Functions.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
1 Chapter 9 Scope, Lifetime, and More on Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Chapter 6: Functions Starting Out with C++ Early Objects
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 8: Functions, File IO.
Current Assignments Homework 3 is due tonight. Iteration and basic functions. Exam 1 on Monday.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
Liang, Introduction to C++ Programming, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Advanced Function Features.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 6 Functions.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
Manish K Parmar PGT (CS) K V VVNagar Thursday, December 24, 2015 Lesson on USER DEFINED FUNCTION IN C++ Presented by Manish K Parmar PGT Computer Science.
FALL 2001ICOM Lecture 01 ICOM 4015 Advanced Programming Lecture 0 Review of Programming I Reading: LNN Chapters 1-3,5-6.
1 09/27/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
2.1 Functions. Functions in Mathematics f x y z f (x, y, z) Domain Range.
1 MODULAR DESIGN AND ABSTRACTION. 2 SPECIFYING THE DETAILS OF A PROBLEM INTO A RELATED SET OF SMALLER PROBLEMS.
1 10/3/05CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
Think First, Code Second Understand the problem Work out step by step procedure for solving the problem (algorithm) top down design and stepwise refinement.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
C++ Programming Lecture 12 Functions – Part IV
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Introduction to Programming
-Neelima Singh PGT(CS) KV Sec-3 Rohini
IS Program Design and Software Tools Introduction to C++ Programming
Chapter 5 Functions.
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 4: Subprograms Functions for Problem Solving
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 9 Scope, Lifetime, and More on Functions
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
Fundamental Programming
ICOM 4015 Advanced Programming
ICOM 4015 Advanced Programming
Standard Version of Starting Out with C++, 4th Edition
Presentation transcript:

FALL 2001ICOM Lecture 21 ICOM 4015 Advanced Programming Lecture 2 Procedural Abstraction Reading: LNN Chapter 4, 14 Prof. Bienvenido Velez

FALL 2001ICOM Lecture 22 Procedural Abstraction Topics Topic 1 –Functions as abstract contracts –Parameter passing –Scoping Topic 2 –Functional arguments Topic 3 –Top-down modular design –Stepwise refinement Topic 4 –Recursive functions –Recursion vs. Iteration Topic 5 –Further procedural abstraction –Function overloading and templates

FALL 2001ICOM Lecture 23 Procedural Abstraction I Outline Functions as abstract contracts Value/Reference parameters Procedural Abstraction Defined Scope Rules

FALL 2001ICOM Lecture 24 Example 0 Finding the roots of ax2 +bx + c #include // roots(a, b, c, r1, r2) - returns the number of // real roots of ax^2 + bx + c. If two roots exists // they are returned is r1 and r2. If only one root // exists, it is returned in r1. Otherwise the value // of r1 and r2 is undetermined. int roots(float a, float b, float c, float& r1, float& r2) { float d = b * b * a * c; if (d < 0) { return 0; } r1 = (-b + sqrt(d)) / (2.0 * a); if (d == 0) { return 1; } r2 = (-b - sqrt(d)) / (2.0 * a); return 2; } roots.cc int roots(float a, float b, float c,float& r1, float& r2); roots.h declarations definitions WHAT? HOW? formal parameters

FALL 2001ICOM Lecture 25 Procedural Abstraction A function should accomplish ONE well defined and easy to remember task A function establishes a contract between callers and implementers The implementer may select any implementation that satisfies the contract. The contract should specify WHAT task the function accomplishes, NOT HOW it accomplishes it “HOW” is hidden or abstracted out, hence the name procedural abstraction

FALL 2001ICOM Lecture 26 Scope Rules & Parameter Passing Mechanisms #include // Forward definitions int f(int& x); // Global definitions static int x = 0; int y = 0; int main() { for (int i=0; i < 5; i++) { int arg = x; int r = f(x); cout " << r; cout << " Glob x=" << x << endl; cout << " Glob y=" << y << endl; } int f(int& x) { int y=0; static int z=0; y++; z+=2; x = y + z; cout << " Loc x=" << x; cout << " Loc y=" << y; cout << " Loc z=" << z; return z; } ~ >> scope1 Loc x=3 Loc y=1 Loc z=2 f(0) -> 2 Glob x=3 Glob y=0 Loc x=5 Loc y=1 Loc z=4 f(3) -> 4 Glob x=5 Glob y=0 Loc x=7 Loc y=1 Loc z=6 f(5) -> 6 Glob x=7 Glob y=0 Loc x=9 Loc y=1 Loc z=8 f(7) -> 8 Glob x=9 Glob y=0 Loc x=11 Loc y=1 Loc z=10 f(9) -> 10 Glob x=11 Glob y=0 ~ >> Global in Module Global Local to For Loop Local to Block Local to Function

FALL 2001ICOM Lecture 27 Diagramas de Bloques main: f: x: y: x: y: z: for: i: arg: r:

FALL 2001ICOM Lecture 28 Procedural Abstraction I Summary of Concepts Value parameters – changes remain local to function. Function works with a copy of the argument. Reference parameters – changes propagate to argument. Function works with original argument. Procedural abstraction – a function establishes a contract with its callers on what it accomplishes, hiding how it accomplishes it.

FALL 2001ICOM Lecture 29 Procedural Abstraction I - Scoping Summary of Concepts II Definition: Scope of a declaration –region of code where declaration is active Scope rules allow better control over the namespace Local namespaces (e.g. functions, blocks) independent of each other Local declarations take precedence over global declarations

FALL 2001ICOM Lecture 210 Procedural Abstraction II Outline Procedural arguments

FALL 2001ICOM Lecture 211 Integration Without Procedural Arguments #include // Forward definitions double integrateSqr(double a, double b, double n); double integrateCube(double a, double b, double n); int main() { cout << "Integral of x^2 in [0,1] = " << integrateSqr(0.0, 1.0, 10000) << endl; cout << "Integral of x^3 in [0,1] = " << integrateCube(0.0, 1.0, 10000) << endl; } double integrateSqr(double a, double b, double n) { double delta = (b-a) / double(n); double sum = 0.0; for (int i=0; i<n; i++) { float x = a + delta * i; sum += x * x * delta; } return sum; } double integrateCube(double a, double b, double n) { double delta = (b-a) / double(n); double sum = 0.0; for (int i=0; i<n; i++) { float x = a + delta * i; sum += x * x * x * delta; } return sum; } ~/icom4015/lec05 >> example2 Integral of x^2 in [0,1] = Integral of x^3 in [0,1] = ~/icom4015/lec05 >>

FALL 2001ICOM Lecture 212 Example 3 Integration With Procedural Arguments #include // Forward definitions double integrate(double a, double b, double n, double f(double x)); double cube(double x); double sqr(double x); int main() { cout << "Integral of x^2 in [0,1] = " << integrate(0.0, 1.0, 10000, sqr) << endl; cout << "Integral of x^3 in [0,1] = " << integrate(0.0, 1.0, 10000, cube) << endl; } double integrate(double a, double b, double n, double f(double x)) { double delta = (b-a) / double(n); double sum = 0.0; for (int i=0; i<n; i++) { sum += f(a + delta * i) * delta; } return sum; } double cube(double x) { return x * x * x; } double sqr(double x) { return x * x; } ~/icom4015/lec05 >> example2 Integral of x^2 in [0,1] = Integral of x^3 in [0,1] = ~/icom4015/lec05 >>

FALL 2001ICOM Lecture 213 Procedural Abstraction II Functional Arguments Summary of Concepts Functional arguments –Allow abstraction over processes and functions

FALL 2001ICOM Lecture 214 Procedural Abstraction III Outline Top-down stepwise refinement

FALL 2001ICOM Lecture 215 Step 0 - Outline // top-down.cc // Computes weighted average score of grades. Grades // include two assignments two midterm exams and one final exam. // All grades are input from standard input, but the weights of // each type of grade are hard coded. // C header files extern "C" { } // Standard C++ header files #include // My own C++ header files // Macro definitions // Forward definitions of auxiliary functions // Global declarations // Main function int main() { // Read assignment grades // Read exam grades // Read final exam grade // Calculate average // Print report return 0; } // Auxiliary functions

FALL 2001ICOM Lecture 216 Step 1 – Code + Stubs int main() { float assignment1, assignment2; float exam1, exam2; float finalExam; readAssignmentGrades(assignment1, assignment2); readExamGrades(exam1, exam2); readFinalGrade(finalExam); float avg; avg = calculateAverage(assignment1, assignment2, exam1, exam2, finalExam); printReport(assignment1, assignment2, exam1, exam2, finalExam, avg); return 0; } // Auxiliary functions void readAssignmentGrades(float& assignment1, float& assignment2) {} void readExamGrades(float& ex1, float& ex2) {} void readFinalGrade(float& final) {} float calculateAverage(float assignment1, float assignment2, float exam1, float exam2, float finalExam) {} void printReport(float assignment1, float assignment2, float exam1, float exam2, float finalExam, float average) {}

FALL 2001ICOM Lecture 217 Step 2 - Refine // Auxiliary functions void readAssignmentGrades(float& assignment1, float& assignment2) { // Read a float in [0,100] into assignment1 // Read a float in [0,100] into assignment2 } void readExamGrades(float& ex1, float& ex2) { // Read a float in [0,100] into ex1 // Read a float in [0,100] into ex2 } void readFinalGrade(float& final) { // Read a float in [0,100] into final } float calculateAverage(float assignment1, float assignment2, float exam1, float exam2, float finalExam) { // Calculate assignments average // Calculate exams average // Calculate weighted average } void printReport(float assignment1, float assignment2, float exam1, float exam2, float finalExam, float average) { // print assignment grades // print exam grades // print final exam grades // print weighted average }

FALL 2001ICOM Lecture 218 Top-down stepwise refinement cycle outline refine code + stubs

FALL 2001ICOM Lecture 219 Procedural Abstraction III Top-down design – Stepwise Refinement Summary of Concepts Top-Down design / stepwise refinement –A cyclic development technique –Each cycle adds a level of detail to the code –We have a functioning (although incomplete) program after every iteration of the process

FALL 2001ICOM Lecture 220 Procedural Abstraction IV Outline Recursive Functions –Activation records, call stacks –Expressiveness of recursion vs. iteration –Efficiency concerns function call overhead duplication of work process complexity

FALL 2001ICOM Lecture 221 Example 0 Factorials // factorials.cc // Implements recursive and interative versions of algorithms for // computing the factorial (N!) of a number. // Standard C++ header files #include // Forward definitions of auxiliary functions long recFactorial(long n); long iterFactorial(long n); int main() { long number; while(true) { cout << "Please enter a positive number (or negative to end): "; cin >> number; if (number < 0) return 0; cout << "Recursive: " << number << "! = " << recFactorial(number) << endl; cout << "Iterative: " << number << "! = " << iterFactorial(number) << endl; } long recFactorial(long n) { if (n==0) { return 1; } else { return (n * recFactorial(n - 1)); } long iterFactorial(long n) { long product = 1; for (long i=1; i<=n; i++) { product *= i; } return product; } ~/icom4015/lec07 >>factorials Please enter a positive number (or negative to end): 3 Recursive: 3! = 6 Iterative: 3! = 6 Please enter a positive number (or negative to end): 4 Recursive: 4! = 24 Iterative: 4! = 24 Please enter a positive number (or negative to end): 5 Recursive: 5! = 120 Iterative: 5! = 120 Please enter a positive number (or negative to end): 6 Recursive: 6! = 720 Iterative: 6! = 720 Please enter a positive number (or negative to end): -1 ~/icom4015/lec07 >>fibonacci

FALL 2001ICOM Lecture 222 Example 1 Fibonacci Numbers // fibonacci.cc // Iterative and recursive algorithms for computing Fibonacci numbers... // Auxiliary Functions long recFibonacci(long n) { if (n==0) { return 0; } else if (n==1) { return 1; } else { return (recFibonacci(n-1) + recFibonacci(n-2)); } long iterFibonacci(long n) { if (n==0) { return 0; } else if (n==1) { return 1; } long F0 = 0; long F1 = 1; long FN; for (long i=1; i<n; i++) { FN = F0 + F1; F0 = F1; F1 = FN; } return FN; } ~/icom4015/lec07 >>fibonacci Please enter a positive number (or negative to end): 3 Recursive: F(3) = 2 Iterative: F(3) = 2 Please enter a positive number (or negative to end): 4 Recursive: F(4) = 3 Iterative: F(4) = 3 Please enter a positive number (or negative to end): 8 Recursive: F(8) = 21 Iterative: F(8) = 21 Please enter a positive number (or negative to end):

FALL 2001ICOM Lecture 223 Example 1 Fibonacci Numbers // fibonacci.cc // Iterative and recursive algorithms for computing Fibonacci numbers // Standard C++ header files #include // Forward definitions of auxiliary functions long recFibonacci(long n); long iterFibonacci(long n); int main() { long number; while(true) { cout << "Please enter a positive number (or negative to end): "; cin >> number; if (number < 0) return 0; cout << "Recursive: F(" << number << ") = " << recFibonacci(number) << endl; cout << "Iterative: F(" << number << ") = " << iterFibonacci(number) << endl; } …...

FALL 2001ICOM Lecture 224 Procedural Abstraction IV Iteration vs. Recursion Summary of Concepts Recursion is as expressive as iteration Iteration can yield faster code –less duplication of work –less function call overhead Recursion can yield cleaner code –may rely on a “smart” optimizing compiler to minimize call overhead

FALL 2001ICOM Lecture 225 Procedural Abstraction V Outline Further procedural abstraction –Function overloading –Function templates

FALL 2001ICOM Lecture 226 Function Overloading SQR Function Family int sqr (int x) { return x * x } long sqr(long x) { return x * x; } float sqr(float x) { return x * x } int intSqr (int x) { return x * x } long longSqr(long x) { return x * x; } float floatSqr(float x) { return x * x } Without overloading With overloading

FALL 2001ICOM Lecture 227 Function Templates SQR Function Family template T sqr (T x) { return x * x } With templates int sqr (int x) { return x * x } long sqr(long x) { return x * x; } float sqr(float x) { return x * x } With overloading

FALL 2001ICOM Lecture 228 SQR’aring different types // Standard C++ header files #include // Forward definitions of local auxiliary functions template T sqr(T x); // Main function int main() { cout << " i" << " sqr(i)" << " sqr(float(i))" << " sqr(double(i))" << endl; for (int i=0; i<10; i++) { cout << setw(16) << i << setw(16) << sqr(i) << setw(16) << sqr(float(i)) << setw(16) << sqr(double(i)) << endl; } // Local auxiliary functions template T sqr(T x) { return x * x; } Templates can reduce code duplication dramatically

FALL 2001ICOM Lecture 229 Output ~/icom4015/lec09 >>sqr i sqr(i) sqr(float(i)) sqr(double(i)) ~/icom4015/lec09 >>

FALL 2001ICOM Lecture 230 Anatomy of a Function Template template function Templates are C++’s implementation of Parametric Polymorphism Inside this function T represents any type T is a type parameter

FALL 2001ICOM Lecture 231 Example 2 // Standard C++ header files #include // Forward definitions of local auxiliary functions template void swap(T& a, T& b); template void doSwap(T a, T b); // Main function int main() { cout << "***** doSwap(1,0)" << endl; doSwap(1,0); cout << endl << endl << "***** doSwap(1.0/3.0, 2.0/3.0)" << endl; doSwap(1.0/3.0, 2.0/3.0); cout << endl << endl << "***** doSwap(true, false)" << endl; doSwap("hello", "world"); } // Local auxiliary functions template void doSwap(T a, T b) { T x = a; T y = b; cout << "x = " << x << " y = " << y << endl; swap(x,y); cout << "swap(x,y)" << endl; cout << "x = " << x << " y = " << y << endl; swap(x,y); cout << "swap(x,y)" << endl; cout << "x = " << x << " y = " << y << endl; } template void swap(T& a, T& b) { T temp = a; a = b; b = temp; } Variable declaration of type T

FALL 2001ICOM Lecture 232 Example 2 Output ~/icom4015/lec09 >>swap ***** doSwap(1,0) x = 1 y = 0 swap(x,y) x = 0 y = 1 swap(x,y) x = 1 y = 0 ***** doSwap(1.0/3.0, 2.0/3.0) x = y = swap(x,y) x = y = swap(x,y) x = y = ***** doSwap(true, false) x = hello y = world swap(x,y) x = world y = hello swap(x,y) x = hello y = world

FALL 2001ICOM Lecture 233 Procedural Abstraction V Function Overloading Summary of Concepts Related functions can be grouped under a common name Overloaded functions may have different return types, but must have different parameters. The importance of overloading will become clearer when we get into classes and object- oriented programming

FALL 2001ICOM Lecture 234 Procedural Abstraction V Function Templates Summary of Concepts Programmer declares one function parameterized over some type T Compiler instantiates potentially many functions for all the different argument types provided among all function calls Instances must be well typed, that is, all objects should only be used according to their types.