1 Storage Classes, Scope, and Recursion Lecture 6.

Slides:



Advertisements
Similar presentations
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
Advertisements

Recursion. Binary search example postponed to end of lecture.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
Programming with Recursion
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Recursion.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.12Recursion 3.13Example Using Recursion: The Fibonacci Series 3.14Recursion.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
CENG 7071 Recursion. CENG 7072 Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type. A recursive function.
Recursion CS Goals Discuss recursion as another form of repetition Do the following tasks, given a recursive routine Determine whether the routine.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 – Recursive Funtions From Deitel’s “C” Book 5.13Recursion 5.14Example Using Recursion: The Fibonacci.
1 C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
Chapter 2 Recursion: The Mirrors CS Data Structures Mehmet H Gunes Modified from authors’ slides.
© 2006 Pearson Addison-Wesley. All rights reserved 3-1 Chapter 3 Recursion: The Mirrors.
12-CRS-0106 REVISED 8 FEB 2013 KUG1C3 Dasar Algoritma dan Pemrograman.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
 2007 Pearson Education, Inc. All rights reserved C Functions.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Lecture6 Recursion function © by Pearson Education, Inc. All Rights Reserved. 1.
Computer Science and Software Engineering University of Wisconsin - Platteville 9. Recursion Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions (Recursion) Outline 5.13Recursion 5.14Example.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 8 Recursion Modified.
 2007 Pearson Education, Inc. All rights reserved C Functions -Continue…-
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
1 Chapter 6 - Functions Outline 6.1Introduction 6.2Program Components in C++ 6.6Math Library Functions 6.4Functions 6.5Function Definitions 6.6Function.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
 2003 Prentice Hall, Inc. All rights reserved. Outline 1 fig02_07.cpp (1 of 2) 1 // Fig. 2.7: fig02_07.cpp 2 // Class average program with counter-controlled.
Lecture 13: Working with Multiple Programmers. Headers Header files: Each standard library has a corresponding header. The function prototype for all.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
 In this chapter you ‘’ll learn: ◦ To construct programs modularly from functions ◦ To use common math library functions ◦ The mechanism for passing.
KIC/Computer Programming & Problem Solving 1.  Header Files  Storage Classes  Scope Rules  Recursion Outline KIC/Computer Programming & Problem Solving.
1 Lecture 3 Part 2 Storage Classes, Scope, and Recursion.
 2003 Prentice Hall, Inc. All rights reserved Storage Classes Variables have attributes –Have seen name, type, size, value –Storage class How long.
A Brief Introduction to Recursion. Recursion Recursive methods … –methods that call themselves! –They can only solve a base case –So, you divide a problem.
C++ Programming Lecture 12 Functions – Part IV
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
12-CRS-0106 REVISED 8 FEB 2013 KUG1C3 Dasar Algoritma dan Pemrograman.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 2 Functions September.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-solving.
Functions Course conducted by: Md.Raihan ul Masood
CISC181 Introduction to Computer Science Dr
IS Program Design and Software Tools Introduction to C++ Programming
C Functions -Continue…-.
CSC113: Computer Programming (Theory = 03, Lab = 01)
FUNCTIONS IN C++.
CSC113: Computer Programming (Theory = 03, Lab = 01)
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 6 - Functions Outline 5.1 Introduction
Announcements Final Exam on August 19th Saturday at 16:00.
Variables have attributes
Function.
1-6 Midterm Review.
Recursive Algorithms 1 Building a Ruler: drawRuler()
Function.
Presentation transcript:

1 Storage Classes, Scope, and Recursion Lecture 6

2 3.10Storage Classes Variables attributes  Name, type, size, value  Storage class How long variable exists in memory (lifetime)  Scope Where variable can be referenced in program  Refers to code blocks  Linkage For multiple-file program (see Ch. 6), which files can use it

3 3.10Storage Classes Static storage class  Variables exist for entire program For functions, name exists for entire program  May not be accessible, scope rules still apply (more later) static keyword  Local variables in function  Keeps value between function calls  Only known in own function

4 3.11Scope Rules Scope  Portion of program where identifier can be used File scope  Defined outside a function, known in all functions  Global variables, function definitions and prototypes Function scope  Can only be referenced inside defining function  Only labels, e.g., identifiers with a colon ( case: )

5 3.11Scope Rules Block scope  Begins at declaration, ends at right brace } Can only be referenced in this range  Local variables, function parameters  static variables still have block scope Storage class separate from scope Function-prototype scope  Parameter list of prototype  Names in prototype optional Compiler ignores  In a single prototype, name can be used once

6 1 // Fig. 3.12: fig03_12.cpp 2 // A scoping example. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 void useLocal( void ); // function prototype 9 void useStaticLocal( void ); // function prototype 10 void useGlobal( void ); // function prototype int x = 1; // global variable int main() 15 { 16 int x = 5; // local variable to main cout << "local x in main's outer scope is " << x << endl; { // start new scope int x = 7; cout << "local x in main's inner scope is " << x << endl; } // end new scope fig03_12.cpp (1 of 5)

7 fig03_12.cpp (2 of 5) cout << "local x in main's outer scope is " << x << endl; useLocal(); // useLocal has local x 31 useStaticLocal(); // useStaticLocal has static local x 32 useGlobal(); // useGlobal uses global x 33 useLocal(); // useLocal reinitializes its local x 34 useStaticLocal(); // static local x retains its prior value 35 useGlobal(); // global x also retains its value cout << "\nlocal x in main is " << x << endl; return 0; // indicates successful termination } // end main 42

8 fig03_12.cpp (3 of 5) 43 // useLocal reinitializes local variable x during each call 44 void useLocal( void ) 45 { 46 int x = 25; // initialized each time useLocal is called cout << endl << "local x is " << x 49 << " on entering useLocal" << endl; 50 ++x; 51 cout << "local x is " << x 52 << " on exiting useLocal" << endl; } // end function useLocal 55

9 fig03_12.cpp (4 of 5) 56 // useStaticLocal initializes static local variable x only the 57 // first time the function is called; value of x is saved 58 // between calls to this function 59 void useStaticLocal( void ) 60 { 61 // initialized only first time useStaticLocal is called 62 static int x = 50; cout << endl << "local static x is " << x 65 << " on entering useStaticLocal" << endl; 66 ++x; 67 cout << "local static x is " << x 68 << " on exiting useStaticLocal" << endl; } // end function useStaticLocal 71

10 fig03_12.cpp (5 of 5) fig03_12.cpp output (1 of 2) 72 // useGlobal modifies global variable x during each call 73 void useGlobal( void ) 74 { 75 cout << endl << "global x is " << x 76 << " on entering useGlobal" << endl; 77 x *= 10; 78 cout << "global x is " << x 79 << " on exiting useGlobal" << endl; } // end function useGlobal local x in main's outer scope is 5 local x in main's inner scope is 7 local x in main's outer scope is 5 local x is 25 on entering useLocal local x is 26 on exiting useLocal local static x is 50 on entering useStaticLocal local static x is 51 on exiting useStaticLocal global x is 1 on entering useGlobal global x is 10 on exiting useGlobal

11 fig03_12.cpp output (2 of 2) local x is 25 on entering useLocal local x is 26 on exiting useLocal local static x is 51 on entering useStaticLocal local static x is 52 on exiting useStaticLocal global x is 10 on entering useGlobal global x is 100 on exiting useGlobal local x in main is 5

12 Recursion Problem solving approach  Repeatedly break problem into smaller versions of the same problem  Goal: reduce problems to trivial size  Repeatedly combine solutions to subproblems Implemented by using functions that call itself on smaller problems

13 Definitions Recursive call  A function call in which the function being called is the same as the one making the call Direct recursion  When the function directly calls itself  This is the type of recursion we will study

14 Pros of Recursion Powerful programming technique to solve problems  Difficult to solve some problems without recursion  Problems can have simple, elegant recursive solutions

15 Classic Recursive Example Consider n! (n factorial)  The number of permutations of n elements  A mathematical description Consider 4!  4! = 4 * 3 * 2 * 1 = 24  Notice 3! = 3 * 2 *1 part of 4!

16 Using Recursion Recursive definition of n! Solve 4!  4! = 4 * 3! 3! = 3 * (3-1)! = 3 * 2!  2! = 2 * (2-1)! = 2 * 1!  1! = 1 * (1-1)! = 1 * 0! o from definition 0! = 1 Report 1 1*1 Report 1 2*1 Report 2 3*2 Report 6 4*6 = 24 stops Notice recursion stops when we reach a case for which we know the answer

17 Recursive Framework Base case  The case for which the solution can be stated nonrecursively General (recursive) case  The case for which the solution is expressed in terms of a smaller version of itself Recursive algorithm  A solution that is expressed in terms of 1. Smaller instances of itself 2. A base case

18 Coding Factorial Function int factorial (int number) { if (number == 0) // base case return 1; else // General case return number * factorial(number -1); } Notice the general case involves the recursive call

19 Verifying Recursive Functions Determine inductively whether a recursive algorithm works The Three-Question Method  Must answer yes to all questions 1. The Base-Case Question  Is there a nonrecursive way out of the function and does the routine work correctly for this base case? 2. The Smaller-Caller Question  Does each recursive call to the function involve a smaller case of the original problem, leading inescapably to the base case? 3. The General-Case Question  Assuming that the recursive call(s) works correctly, does the entire function work correctly?

20 Writing Recursive Functions 1. Get an exact definition of the problem to be solved 2. Determine the size of the problem to be solved on this call to the function. On the initial call to the function, the size of the whole problem is expressed in the value(s) of the parameters(s) 3. Identify and solve the base case(s) in which the problem can be expressed nonrecursively. 4. Identify and solve the general case(s) correctly in terms of a smaller case of the same problem – a recursive call.

21 Multiplying Rabbits (The Fibonacci Sequence) “Facts” about rabbits  Rabbits never die  A rabbit reaches sexual maturity exactly two months after birth, that is, at the beginning of its third month of life  At the beginning of every month, each sexually mature male-female pair gives birth to exactly one male-female pair

22 How many pairs of rabbits are alive in month n? Write a function that finds the nth number in the Fibonacci Series  0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 fibonacci(0) = fibonacci(1) = Function int fibonacci( int n ) { }

23 Writing Recursive Functions 1. Get an exact definition of the problem to be solved 2. Determine the size of the problem to be solved on this call to the function. On the initial call to the function, the size of the whole problem is expressed in the value(s) of the parameters(s) 3. Identify and solve the base case(s) in which the problem can be expressed nonrecursively. 4. Identify and solve the general case(s) correctly in terms of a smaller case of the same problem – a recursive call.

24 Verify fibonacci The Three-Question Method 1. The Base-Case Question  Is there a nonrecursive way out of the function and does the routine work correctly for this base case? 2. The Smaller-Caller Question  Does each recursive call to the function involve a smaller case of the original problem, leading inescapably to the base case? 3. The General-Case Question  Assuming that the recursive call(s) works correctly, does the entire function work correctly?

25 Evaluating code int main() { cout << myst(4, 2) << endl; } int myst(int i, int j) if (i == j) return 1; else if (j == 0) return 1; else return myst(i-1, j-1) + myst(i-1, j); }

Recursion vs. Iteration Repetition  Iteration: explicit loop  Recursion: repeated function calls Termination  Iteration: loop condition fails  Recursion: base case recognized Both can have infinite loops Balance between performance (iteration) and good software engineering (recursion)

27 Tower of Hanoi Problem: Move disks of different sizes from one beg to another  Never have a larger disk on top of a smaller disk on top of a smaller disk  Have 3 pegs to work with

28 The Towers of Hanoi Figure 2.19c and d c) move one disk from A to B; d) move n - 1 disks from C to B