Variable Scope Storage Class Recursion

Slides:



Advertisements
Similar presentations
Modular Programming With Functions
Advertisements

Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Overview creating your own functions calling your own functions.
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
Computer Science 1620 Function Scope & Global Variables.
 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.
Overview scope - determines when an identifier can be referenced in a program storage class - determines the period of time during which that identifier.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
CS 1400 Chap 6 Functions. Library routines are functions! root = sqrt (a); power = pow (b, c); function name argument arguments.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
Call-by-Value vs. Call-by-Reference Call-by-value parameters are used for passing information from the calling function to the called function (input parameters).
1 Chapter 9 Scope, Lifetime, and More on Functions.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
© 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.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Functions Kernighan/Ritchie: Kelley/Pohl: Chapter 4 Chapter 5.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
CPS120: Introduction to Computer Science Decision Making in Programs.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 13 Thanks for lecture slides: Prentice Hall, Inc., 2. C++
EPSII 59:006 Spring Call-by-value example #include void increment(int); //prototype for increment function int main(void) { int a=1; printf("Value.
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
KIC/Computer Programming & Problem Solving 1.  Header Files  Storage Classes  Scope Rules  Recursion Outline KIC/Computer Programming & Problem Solving.
#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.
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.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Chapter 6: Function Introduction to function Standard functions User defined functions –function prototype –function definition Function call Storage classes.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 12.
1 Chapter 9 Scope, Lifetime, and More on Functions.
1 Scope Lifetime Functions (the Sequel) Chapter 8.
C++ Programming Lecture 12 Functions – Part IV
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
A First Book of ANSI C Fourth Edition
1 C++ Classes & Object Oriented Programming Overview & Terminology.
Functions Modules in C++ are called functions and classes. Main reason to use functions is : – get aid in conceptual organization.
 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.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
APS105 Functions (and Pointers) 1. Modularity –Break a program into manageable parts (modules) –Modules interoperate with each other Benefits of modularity:
User-Written Functions
C Functions -Continue…-.
ㅎㅎ Fourth step for Learning C++ Programming Namespace Function
A Lecture for the c++ Course
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 5 - Functions Outline 5.1 Introduction
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 9 Scope, Lifetime, and More on Functions
User Defined Functions
C++ Pointers and Strings
Functions Imran Rashid CTO at ManiWeber Technologies.
CS1201: Programming Language 2
Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.
C++ Pointers and Strings
Presentation transcript:

Variable Scope Storage Class Recursion C++ Functions Variable Scope Storage Class Recursion C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 In other languages called subroutines or procedures. C++ functions all have a type. Sometimes we don’t need to have a function return anything – in this case the function can have type void. C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 C++ Functions (cont.) C++ functions have a list of parameters. Parameters are the things we give the function to operate on. Each parameter has a type. There can be zero parameters. C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Sample function Return type parameters Function name int add2ints(int a, int b) { return(a+b); } Function body C++ Functions SarMag Trimester 3

Using functions – Math Library functions C++ includes a library of Math functions you can use. You have to know how to call these functions before you can use them. You have to know what they return. You don’t have to know how they work! C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 double sqrt( double ) When calling sqrt, we have to give it a double. The sqrt function returns a double. We have to give it a double. x = sqrt(y); x = sqrt(100); C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 x = sqrt(y); The stuff we give a function is called the argument(s). Y is the argument here. A C++ function can’t change the value of an argument! If y was 100 before we call sqrt, it will always be 100 after we call sqrt. C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Table of square roots int i; for (i=1;i<10;i++) cout << sqrt(i) << endl; But I thought we had to give sqrt() a double? C++ does automatic type conversion for you. C++ Functions SarMag Trimester 3

Telling the compiler about sqrt() How does the compiler know about sqrt ? You have to tell it: #include <math.h> Try out the sqrt_table program at http://www.cs.rpi.edu/~hollingd/cpp/code. Try it without the include and with the include. C++ Functions SarMag Trimester 3

Other Math Library Functions ceil floor cos sin tan exp log log10 pow fabs fmod C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Writing a function You have decide on what the function will look like: Return type Name Types of parameters (number of parameters) You have to write the body (the actual code). C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Function parameters The parameters are local variables inside the body of the function. When the function is called they will have the values passed in. The function gets a copy of the values passed in (we will later see how to pass a reference to a variable). C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Sample Function int add2nums( int firstnum, int secondnum ) { int sum; sum = firstnum + secondnum; // just to make a point firstnum = 0; secondnum = 0; return(sum); } Available via the course home page in code/functions/add2nums.cpp C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Testing add2nums int main() { int y,a,b; cout << "Enter 2 numbers\n"; cin >> a >> b; y = add2nums(a,b); cout << "a is " << a << endl; cout << "b is " << b << endl; cout << "y is " << y << endl; return(0); } C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 What happens here? int add2nums(int a, int b) { a=a+b; return(a); } … int a,b,y; y = add2nums(a,b); C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Local variables Parameters and variables declared inside the definition of a function are local. They only exist inside the function body. Once the function returns, the variables no longer exist! That’s fine! We don’t need them anymore! C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Block Variables You can also declare variables that exist only within the body of a compound statement (a block): { int foo; … } C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Global variables You can declare variables outside of any function definition – these variables are global variables. Any function can access/change global variables. Example: flag that indicates whether debugging information should be printed. C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Scope The scope of a variable is the portion of a program where the variable has meaning (where it exists). A global variable has global (unlimited) scope. A local variable’s scope is restricted to the function that declares the variable. A block variable’s scope is restricted to the block in which the variable is declared. C++ Functions SarMag Trimester 3

A note about Global vs. File scope A variable declared outside of a function is available everywhere, but only the functions that follow it in the file know about it. The book talks about file scope, I’m calling it global scope. C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Block Scope int main(void) { int y; int a = y; cout << a << endl; } Error – a doesn’t exist outside the block! C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Nesting In C++: There is no nesting of function definitions. You don’t need to know who calls a function to know the scope of it’s variables! There is nesting of variable scope in blocks. C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Nested Blocks void foo(void){ for (int j=0;j<10;j++) { int k = j*10; cout << j << “,” << k << endl; { int m = j+k; cout << m << “,” << j << endl; } j k m Available on the course home page in code/functions/blockscope.cpp C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Storage Class Each variable has a storage class. Determines the period during which the variable exists in memory. Some variables are created only once (memory is set aside to hold the variable value) Global variables are created only once. Some variables are re-created many times Local variables are re-created each time a function is called. C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Storage Classes auto – created each time the block in which they exist is entered. register – same as auto, but tells the compiler to make as fast as possible. static – created only once, even if it is a local variable. extern – global variable declared elsewhere. C++ Functions SarMag Trimester 3

Specifying Storage Class auto int j; register int i_need_to_be_fast; static char remember_me; extern double a_global; C++ Functions SarMag Trimester 3

Practical Use of Storage Class Local variables are auto by default. Global variables are static by default. Declaring a local variable as static means it will remember it’s last value (it’s not destroyed and recreated each time it’s scope is entered). C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 static example int countcalls(void) { static int count = 0; count++; return(count); } … cout << countcalls() << endl; Available on the course home page in code/functions/countcalls.cpp C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 The Scope of Functions In C++ we really talk about the scope of an identifier (name). Could be a function or a variable (or a class). Function names have file scope everything that follows a function definition in the same file can use the function. Sometimes this is not convenient We want to call the function from the top of the file and define it at the bottom of the file. C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Function Prototypes A Function prototype can be used to tell the compiler what a function looks like So that it can be called even though the compiler has not yet seen the function definition. A function prototype specifies the function name, return type and parameter types. C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Example prototypes double sqrt( double); int add2nums( int, int); int counter(void); C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Using a prototype int counter(void); int main(void) { cout << counter() << endl; } int counter(void) static int count = 0; count++; return(count); C++ Functions SarMag Trimester 3

Functions that call each other foo1 … foo2() foo2 … foo1() C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Dualing Functions char *chicken( int generation ) { if (generation == 0) return("Chicken!"); else return(egg(generation-1)); } char *egg( int generation ) { if (generation == 0) return("Egg!"); else return(chicken(generation-1)); } Code is available on the course web site in code/functions/dualing.cpp C++ Functions SarMag Trimester 3

The rest of chicken vs. egg char *egg( int ); char *chicken( int ); int main(void) { int startnum; cout << "Enter starting generation of your chicken" << endl; cin >> startnum; cout << "Your chicken started as a " << chicken(startnum) << endl; return(0); } dualing.cpp C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Recursion Functions can call themselves! This is called recursion. Recursion is very useful – it’s often very simple to express a complicated computation recursively. C++ Functions SarMag Trimester 3

The Recursive Chicken (a new dance fad!) char *chicken_or_egg( int gen ) { if (gen == 0) return("Chicken!"); else if (gen == 1) return(“Egg!”); else return(chicken_or_egg(gen-1)); } C++ Functions SarMag Trimester 3

A Better Example - Computing Factorials int factorial( int x ) { if (x == 1) return(1); else return(x * factorial(x-1)); } Available on the course home page in code/functions/factorias.cpp C++ Functions SarMag Trimester 3

Designing Recursive Functions Define “Base Case”: The situation in which the function does not call itself. Define “recursive step”: Compute the return value the help of the function itself. C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Recursion Base Case The base case corresponds to a case in which you know the answer (the function returns the value immediately), or can easily compute the answer. If you don’t have a base case you can’t use recursion! (and you probably don’t understand the problem). C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Recursive Step Use the recursive call to solve a sub-problem. The parameters must be different (or the recursive call will get us no closer to the solution). You generally need to do something besides just making the recursive call. C++ Functions SarMag Trimester 3

Recursion is a favorite test topic Write a recursive C++ function that computes the area of an nxn square. n Base case: n=1 area=1 Recursive Step: area = n+n-1+area(n-1) C++ Functions SarMag Trimester 3

Recursive area function int area( int n) { if (n == 1) return(1); else return( n + n - 1 + area(n-1) ); } C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Recursion Exercise Write a function that prints a triangle: triangle(4); triangle(5); * * *** *** ***** ***** ******* ******* ********* C++ Functions SarMag Trimester 3

Call-by-value vs. Call-by-reference So far we looked at functions that get a copy of what the caller passed in. This is call-by-value, as the value is what gets passed in (the value of a variable). We can also define functions that are passed a reference to a variable. This is call-by-reference, the function can change a callers variables directly. C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 References A reference variable is an alternative name for a variable. A shortcut. A reference variable must be initialized to reference another variable. Once the reference is initialized you can treat it just like any other variable. C++ Functions SarMag Trimester 3

Reference Variable Declarations To declare a reference variable you precede the variable name with a “&”: int &foo; double &blah; char &c; C++ Functions SarMag Trimester 3

Reference Variable Example int count; int &blah = count; // blah is the same variable as count count = 1; cout << “blah is “ << blah << endl; blah++; cout << “count is “ << count << endl; Code is on the course home page in code/functions/testref.cpp C++ Functions SarMag Trimester 3

C++ Functions SarMag Trimester 3 Reference Parameters You can declare reference parameters: void add10( int &x) { x = x+10; } … add10(counter); The parameter is a reference Code is on the course home page in code/functions/testref.cpp C++ Functions SarMag Trimester 3

Useful Reference Example void swap( int &x, int &y) { int tmp; tmp = x; x = y; y = tmp; } C++ Functions SarMag Trimester 3