Fundamentals of Programming Session 13

Similar documents
142

Fundamentals of Programming Session 12

C Functions. Object created and destroyed within its block auto: default for local variables

Fundamentals of Programming Session 25

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Fundamentals of Programming Session 15

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Fundamentals of Programming Session 23

Chapter 3 - Functions

Functions and Recursion

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

C: How to Program. Week /Apr/16

C++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved.

Fundamentals of Programming Session 4

Loops / Repetition Statements

Lecture 04 FUNCTIONS AND ARRAYS

Fundamentals of Programming Session 8

Fundamentals of Programming Session 7

Iterative Languages. Scoping

Function Call Stack and Activation Records

Day08 A. Young W. Lim Mon. Young W. Lim Day08 A Mon 1 / 27

CSE123. Program Design and Modular Programming Functions 1-1

Fundamentals of Programming Session 24

Lecture 04 FUNCTIONS AND ARRAYS

Fundamentals of Programming Session 9

Fundamentals of Programming Session 20

Methods (Deitel chapter 6)

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Repetition Structures

Fundamentals of Programming Session 19

Methods (Deitel chapter 6)

A Fast Review of C Essentials Part II

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Programming Languages

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Unit 7. Functions. Need of User Defined Functions

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

Chapter 2: Functions and Control Structures

Introduction. C provides two styles of flow control:

Introduction to Programming session 24

CSE 230 Intermediate Programming in C and C++ Recursion

C Functions Pearson Education, Inc. All rights reserved.

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Flow Control. CSC215 Lecture

Introduction to Programming

Fundamentals of Programming Session 20

REPETITION CONTROL STRUCTURE LOGO

Tail Recursion. ;; a recursive program for factorial (define fact (lambda (m) ;; m is non-negative (if (= m 0) 1 (* m (fact (- m 1))))))

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

Loops / Repetition Statements

Fundamentals of Programming Session 2

The for Loop. Lesson 11

Fundamentals of Programming Session 14

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Chapter 3 - Functions

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Fundamentals of Programming Session 24

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Fundamentals of Programming Session 19

Decision Making in C

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

FORM 2 (Please put your name and form # on the scantron!!!!)

Introduction to the Java Basics: Control Flow Statements

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

Recap: Assignment as an Operator CS 112 Introduction to Programming

For searching and sorting algorithms, this is particularly dependent on the number of data elements.

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

CSI33 Data Structures

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

IT 374 C# and Applications/ IT695 C# Data Structures

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Introduction to Programming

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Math Modeling in Java: An S-I Compartment Model

Lecture 7 Tao Wang 1

CS 112 Introduction to Programming

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

8. Control statements

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Module 4: Decision-making and forming loops

Recursion Introduction OBJECTIVES

CS110D: PROGRAMMING LANGUAGE I

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Recursive Definitions

Chapter 7 Functions. Now consider a more advanced example:

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Lab 09: Advanced SQL

Transcription:

Fundamentals of Programming Session 13 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology

Outlines Scope Rules Recursion Example Using Recursion: Fibonacci Series 2

Scope Rules 3 The scope of an identifier is the portion of the program in which the identifier can be referenced. For example, when we define a local variable in a block, it can be referenced only following its definition in that block or in blocks nested within that block. The four identifier scopes are function scope, file scope, block scope, and function-prototype scope. Labels (an identifier followed by a colon such as start:) are the only identifiers with function scope. Labels are used in switch statements (as case labels) and in goto statements.

Scope Rules 4 An identifier declared outside any function has file scope. Such an identifier is known (i.e., accessible) in all functions from the point at which the identifier is declared until the end of the file. Global variables, function definitions, and function prototypes placed outside a function all have file scope. Identifiers defined inside a block have block scope. Block scope ends at the terminating right brace (}) of the block. Local variables defined at the beginning of a function have block scope as do function parameters, which are considered local variables by the function. Any block may contain variable definitions.

Scope Rules When blocks are nested, and an identifier in an outer block has the same name as an identifier in an inner block, the identifier in the outer block is hidden until the inner block terminates. This means that while executing in the inner block, the inner block sees the value of its own local identifier and not the value of the identically named identifier in the enclosing block. Local variables declared static still have block scope, even though they exist from the time the program begins execution. 5

Scope Rules Thus, storage duration does not affect the scope of an identifier. The only identifiers with function-prototype scope are those used in the parameter list of a function prototype. As mentioned previously, function prototypes do not require names in the parameter list only types are required. If a name is used in the parameter list of a function prototype, the compiler ignores the name. 6 Identifiers used in a function prototype can be reused elsewhere in the program without ambiguity.

Scope Rules 7 Figure 5.12 demonstrates scoping issues with global variables, automatic local variables, and static local variables. A global variable x is defined and initialized to 1 (line 9). This global variable is hidden in any block (or function) in which a variable named x is defined. In main, a local variable x is defined and initialized to 5 (line 14). This variable is then printed to show that the global x is hidden in main. Next, a new block is defined in main with another local variable x initialized to 7 (line 19).

Scope Rules 8 This variable is printed to show that it hides x in the outer block of main. The variable x with value 7 is automatically destroyed when the block is exited, and the local variable x in the outer block of main is printed again to show that it s no longer hidden. The program defines three functions that each take no arguments and return nothing. Function uselocal defines an automatic variable x and initializes it to 25 (line 40). When uselocal is called, the variable is printed, incremented, and printed again before exiting the function.

Scope Rules Therefore, when it refers to variable x, the global x (line 9) is used. When useglobal is called, the global variable is printed, multiplied by 10, and printed again before exiting the function. The next time function useglobal is called, the global variable still has its modified value, 10. Finally, the program prints the local variable x in main again (line 33) to show that none of the function calls modified the value of x because the functions all referred to variables in other scopes. 9

10 Scope Rules

11 Scope Rules

12 Scope Rules

13 Scope Rules

Recursion A recursive function is a function that calls itself either directly or indirectly through another function. A recursive function is called to solve a problem. The function actually knows how to solve only the simplest case(s), or so-called base case(s). If the function is called with a base case, the function simply returns a result. If the function is called with a more complex problem, the function divides the problem into two conceptual pieces: a piece that the function knows how to do and a piece that it does not know how to do. 14 Because this new problem looks like the original problem, the function launches (calls) a fresh copy of itself to go to work on the smaller problem this is referred to as a recursive call and is also called the recursion step.

Recursion The factorial of a nonnegative integer n, written n! (and pronounced n factorial ), is the product n (n 1) (n 2) 1 with 1! equal to 1, and 0! defined to be 1. The factorial of an integer, number, greater than or equal to 0 can be calculated iteratively (nonrecursively) using a for statement as follows: factorial = 1; for ( counter = number; counter >= 1; counter-- ) factorial *= counter; 15

16 Recursion

17 Recursion

18 Recursion

Recursion 19 The conversion specifier %ld is used to print long values. Unfortunately, the factorial function produces large values so quickly that even long int does not help us print many factorial values before the size of a long int variable is exceeded. As we ll explore in the exercises, double may ultimately be needed by the user desiring to calculate factorials of larger numbers. This points to a weakness in C (and most other procedural programming languages), namely that the language is not easily extended to handle the unique requirements of various applications.

Example Using Recursion: Fibonacci Series The Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, 21, begins with 0 and 1 and has the property that each subsequent Fibonacci number is the sum of the previous two Fibonacci numbers. The Fibonacci series may be defined recursively as follows: fibonacci(0) = 0 fibonacci(1) = 1 fibonacci(n) = fibonacci(n 1) + fibonacci(n 2) 20 Figure 5.15 calculates the n th Fibonacci number recursively using function fibonacci.

21 Example Using Recursion: Fibonacci Series

22 Example Using Recursion: Fibonacci Series

23 Example Using Recursion: Fibonacci Series

24 Example Using Recursion: Fibonacci Series

25 Example Using Recursion: Fibonacci Series

Example Using Recursion: Fibonacci Series 26 Each level of recursion in the fibonacci function has a doubling effect on the number of calls; i.e., the number of recursive calls that will be executed to calculate the n th Fibonacci number is on the order of 2 n. This rapidly gets out of hand. Computer scientists refer to this as exponential complexity. Problems of this nature humble even the world s most powerful computers! Complexity issues in general, and exponential complexity in particular, are discussed in detail in the upper-level computer science curriculum course generally called Algorithms.

Recursion vs. Iteration 27 In the previous sections, we studied two functions that can easily be implemented either recursively or iteratively. Both iteration and recursion are based on a control structure: Iteration uses a repetition structure; recursion uses a selection structure. Both iteration and recursion involve repetition: Iteration explicitly uses a repetition structure; recursion achieves repetition through repeated function calls. Iteration and recursion each involve a termination test: Iteration terminates when the loop-continuation condition fails; recursion terminates when a base case is recognized. Both iteration and recursion can occur infinitely: An infinite loop occurs with iteration if the loop-continuation test never becomes false; infinite recursion occurs if the recursion step does not reduce the problem each time in a manner that converges on the base case.

Recursion vs. Iteration Recursion has many negatives. It repeatedly invokes the mechanism, and consequently the overhead of function calls. This can be expensive in both processor time and memory space. Each recursive call causes another copy of the function (actually only the function s variables) to be created; this can consume considerable memory. Iteration normally occurs within a function, so the overhead of repeated function calls and extra memory assignment is omitted. So why choose recursion? 28

29 Recursion vs. Iteration

30 Recursion vs. Iteration