 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 1 3.1Introduction Divide and Conquer –Construct a program from smaller.

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

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
 2003 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
Function Introduction
 2007 Pearson Education, Inc. All rights reserved C Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions.
 2007 Pearson Education, Inc. All rights reserved C Functions.
1 Review (Week1) C++_ the unit of programming is the class from which objects are eventually instantiated. C++ classes contain functions that implement.
 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.
Functions. 3Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece more manageable than the original program.
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. Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function.
1 Lecture 3 Part 1 Functions with math and randomness.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Main Objectives: To understand how to construct programs modularly from.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
© 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.
Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files.
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.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 15 - C++ As A "Better C" Outline 15.1Introduction 15.2C A Simple Program: Adding Two Integers.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 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.
1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions 3.4Functions 3.5Function Definitions 3.6Function.
 In this chapter you ‘’ll learn: ◦ To construct programs modularly from functions ◦ To use common math library functions ◦ The mechanism for passing.
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
EPSII 59:006 Spring Call-by-value example #include void increment(int); //prototype for increment function int main(void) { int a=1; printf("Value.
KIC/Computer Programming & Problem Solving 1.  Header Files  Storage Classes  Scope Rules  Recursion Outline KIC/Computer Programming & Problem Solving.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions.
 2003 Prentice Hall, Inc. All rights reserved Storage Classes Variables have attributes –Have seen name, type, size, value –Storage class How long.
 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 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.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 2 Functions September.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Introduction Program Components in C++ Math Library Functions Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
Functions Course conducted by: Md.Raihan ul Masood
Functions.
Dr. Shady Yehia Elmashad
CISC181 Introduction to Computer Science Dr
IS Program Design and Software Tools Introduction to C++ Programming
Functions and an Introduction to Recursion
Chapter 3 - Functions Outline 3.1 Introduction
CSC113: Computer Programming (Theory = 03, Lab = 01)
CSC113: Computer Programming (Theory = 03, Lab = 01)
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 3 - Functions Outline 3.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions Najah Alsubaie Kingdom of Saudi Arabia
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 3 - Functions Outline 3.1 Introduction
توابع در C++ قسمت اول اصول كامپيوتر 1.
Chapter 3 - Functions Outline 3.1 Introduction
Chapter 6 - Functions Outline 5.1 Introduction
Chapter 3 - Functions Outline 3.1 Introduction
Variables have attributes
Chapter 15 - C++ As A "Better C"
Chapter 3 - Functions Outline 3.1 Introduction
Presentation transcript:

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 1 3.1Introduction Divide and Conquer –Construct a program from smaller pieces or components –Each piece more manageable than the original program Functions –Name of a small program or piece of code that does a specific thing Benefits of using functions –Allows reuse of code –Easy to maintenance –Makes code easy to read and understand

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 2 FunctionsFunctions Functions contain –Data – declarations int i, j, k; –Code - executable statements (“if”, “case”, “assignment”, “for”, “while”,“do- while”, ……) Data may be declared anywhere in the function, as long as it is declared before it is used

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 3 3.3Math Library Functions Math library functions –Allows programmer to perform common mathematical calculations –Must include the header file Functions called by writing var = functionName (argument); Example cout << sqrt( ); –Calls the sqrt (square root) function. The preceding statement would print 30 –The sqrt function takes an argument of type double and returns a result of type double, as do all functions in the math library

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 4 3.3Math Library Functions Function arguments can be –Constants sqrt( 4 ); –Variables sqrt( x ); –Expressions sqrt( sqrt( x ) ) ; sqrt( 3 - 6x ); –Identifiers (variable name or name of a built-in function) sqrt( fSomeNum ); –Identifiers must begin with a character or underscore which can then be followed by characters, underscores, and numbers Examples of Math lib functions –acos, asin, atan, atan2, cos, cosh, sin, sinh, tan, tanh

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 5 FunctionsFunctions Functions have a general form (parameter list) { … } Functions MUST be declared before they are used. This is commonly referred to as prototyping. Only exception is function main. It does not have to be declared int main (void) { … return 0 }

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 6 Formal Parameters Formal parameters are used to declare variables which are arguments to functions They can be used like any other variables within a function Do not declare a local variable with the same name as a formal parameter! sqr = Square(5); //called from main like this int Square (int num) { int result = num * num; return result; } num is a formal parameter.

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Function Definitions Purpose of a function is to –Take in data (via formal parameters) –Perform operations –Return the result Format for function definition : return-value-type function-name(parameter-list) { declarations and statements return } Example : int square( int y) { int x = y * y; return x; }

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 8 Function Protypes All functions other than main should be declared before they can be used This declaration is called a prototype A prototype contains –Function return type –Function name –Function parameter (list of var type and var name) Variable Types –Like int, double, etc. Variable Names –In function prototype, parameter names are optional, but good programming practice to use them

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 9 3.6Function Prototypes –Function parameter Information the function takes in –Return type Type of information the function passes back to caller (default int ) void signifies the function returns nothing –Function prototype is only needed if function definition comes after the function call in the program

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 10 Functions – Scope #include using namespace std; int Product (int x, int y); Function Prototype int i = 10; // Global variable, defined before main int n = 20; // Global variable, defined before main int main (void) // main Program starts here { int j = 5, i = 6, k = 0; // declare and initialize variables k = Product (i, j); cout << “k = “ << k << “, n = " << n << endl; return 0; } // main Program ends here int Product (int x, int y) // function definition { int i; i = x * y; cout << “Local i = “ << i << ", Global i = “<< ::i << endl; cout << "n = " << n << endl; return i; }

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 11 Returning from a Function A return statement is used to exit a function, from within any code block in the function Good programming style says there should be only 1 return statement (may not be practical) Void functions do not require a “return” but should be coded with a “return” without any arguments. Other functions should have a “return” with a value. Without a value, compiler will issue warning

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 12 Return statement The “return” statements does not require parenthesis and may contain executable statements within it: return 1; return (max(a,b)); return ;

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 13 Scope Rules for Functions Scope determines the “lifetime” of a variable There are 3 types of variables Local Variables –Declared inside a function (main is also a function) –Scope is only during the execution of that function –Accessible only inside the function in which they are declared –All variables declared in function definitions are local variables for that function Formal Parameters –defines a list of variables that are passed to a function –Local variables are passed when function is called. This provides a function with outside information.

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 14 Scope Rules for Functions Global variables –Are declared before the main program –Variable’s lifetime can last throughout the program –Accessible by all the functions Scope determines “accessibility” of a variable –Local - Accessible only in the function it is declared in –Declared in main - Not accessible by functions –Declared in function - Not accessible by main –Declared before main – accessible by all

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 15 Local Variables Local variables can be declared anywhere inside of a function They are created and destroyed each time the code block in which they are declared, is entered or exited void graph () { int i;// creates i i = 5;// uses i { int i = 7;// creates another i cout << i << endl; // will print 7 } // destroys inner i cout << i << endl; // will print 5, not 7 }

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 16 Global Variables and Functions Global variables are declared outside of functions They can be accessed anywhere from within a function Be careful not to hide global variables !! double size = 5, height = 10; void box (float width) { cout << size << endl; // prints global 5 { double size = 7; // creates new “size” cout << size << endl; // prints local 7 height = 31; //dangerous, global var changed } cout << size << endl; // prints global 5 }

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 17 Scope rule in For Loop The “for” statement allows for variables to be declared in the initialization of the loop –Be very careful, they are compiler dependent!!!! Compiler A: for (int i=0; i < 20; i++) { ……. } cout << i << endl; //Valid int i is not destroyed (MS VC++) Compiler B: for (int i=0; i < 20; i++) { } cout << i << endl; // invalid - i is destroyed when “for” ends

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 18 Scope rule for variables The C++ standard allows variables to be declared within conditional expressions such as “if” and “while” while (float y = x) > sqrt(j)); // Declares y. if ((float x = y) < 5.0) // declares x, initializing it to y {. } x = 7.5; // Error ! X no longer exists

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Function prototype 2. Loop 3. Function definition Program Output 1// Fig. 3.3: fig03_03.cpp 2// Creating and using a programmer-defined function 3#include 4 5using std::cout; 6using std::endl; 7 8int square( int y); // function prototype 9 10int main() 11{ 12 for ( int x = 1; x <= 10; x++ ) 13 cout << square( x ) << " "; cout << endl; 16 return 0; 17} 18 19// Function definition 20int square( int y ) 21{ 22 return y * y; 23} Notice how parameters and return value are declared.

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Function prototype (3 parameters) 2. Input values 2.1 Call function 1// Fig. 3.4: fig03_04.cpp 2// Finding the maximum of three integers 3#include 4 5using std::cout; 6using std::cin; 7using std::endl; 8 9int maximum( int, int, int ); // function prototype 10 11int main() 12{ 13 int a, b, c; cout << "Enter three integers: "; 16 cin >> a >> b >> c; // a, b and c below are arguments to 19 // the maximum function call 20 cout<< "Maximum is: " << maximum(a,b,c) << endl;

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Function definition Program Output return 0; 23} 24 25// Function maximum definition 26// x, y and z below are parameters to 27// the maximum function definition 28int maximum( int x, int y, int z ) 29{ 30 int max = x; if ( y > max ) 33 max = y; if ( z > max ) 36 max = z; return max; 39} Enter three integers: Maximum is: 85 Enter three integers: Maximum is: 92 Enter three integers: Maximum is: 98

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 22 Function Arguments By Value –When arguments are passed to a function, a temporary copy (duplicate) of the arguments is given to the functions. Original values remain unchanged By Reference –Actual address of the variable is given to the function. When a function modifies this value, it is changed in the function and in the main (like a global variable was changed). Except for arrays, by default, C++ passes arguments by value. This can be very inefficient when large items are passed When an item is large, or must be modified by the function, the argument can be passed by reference (address)

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Header Files Header files –Contain function prototypes for library functions –,, etc. –Load with #include Example: #include Custom header files –Defined by the programmer –Save as filename.h –Loaded into program using #include "filename.h"

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Random Number Generation rand function i = rand(); –Load –Generates a pseudo random number between 0 and RAND_MAX (usually 32767) A pseudorandom number is a preset sequence of "random" numbers The same sequence is generated upon every program execution srand function –Jumps to a seeded location in a "random" sequence srand( seed ); srand( time( 0 ) ); //must include –time( 0 ) The time at which the program was compiled –Changes the seed every time the program is compiled, thereby allowing rand to generate random numbers

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Random Number Generation Scaling –Reduces random number to a certain range –Modulus ( % ) operator Reduces number between 0 and RAND_MAX to a number between 0 and the scaling factor –Example i = rand() % 6; Generates a number between 0 and 5 i = 1 + (rand() % 6); Generates a number between 1 and 6

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Define loop 2. Output random number Program Output // Fig. 3.7: fig03_07.cpp 2// Shifted, scaled integers produced by 1 + rand() % 6 3#include 4 5using std::cout; 6using std::endl; 7 8#include 9 10using std::setw; 11 12#include 13 14int main() 15{ 16 for ( int i = 1; i <= 20; i++ ) { 17 cout << setw( 10 ) << ( 1 + rand() % 6 ); if ( i % 5 == 0 ) 20 cout << endl; 21 } return 0; 24} Notice rand() % 6. This returns a number between 0 and 5 (scaling). Add 1 to get a number between 1 and 6. Executing the program again gives the same "random" dice rolls.

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Initialize seed 2. Input value for seed 2.1 Use srand to change random sequence 2.2 Define Loop 3. Generate and output random numbers 1) // Fig. 3.9: fig03_09.cpp 2) // Randomizing die-rolling program 3) #include 4) 5) using std::cout; 6) using std::cin; 7) using std::endl; 8) 9) #include 10) 11) using std::setw; 12) 13) #include 14) 15) int main() 16) { 17) unsigned seed; 18) 19) cout > seed; 21) srand( seed ); 22) 23) for ( int i = 1; i <= 10; i++ ) { 24) cout << setw( 10 ) << 1 + rand() % 6; 25) 26) if ( i % 5 == 0 ) 27) cout << endl; 28) } 29) 30) return 0; 31) }

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Program Output Enter seed: Enter seed: Enter seed: Notice how the die rolls change with the seed.

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Example: A Game of Chance and Introducing enum Enumeration - set of integers with identifiers enum typeName { constant1, constant2 …}; –Constants start at 0 (default), incremented by 1 –Unique constant names –Example: enum Status {CONTINUE, WON, LOST}; Create an enumeration variable of type typeName –Variable is constant, its value may not be reassigned Status enumVar; // create variable enumVar = WON; // set equal to WON enumVar = 1; // ERROR

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 30 Example: A Game of Chance and Introducing enum(II) Enumeration constants can have values pre-set enum Months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; –Starts at 1, increments by 1 Craps simulator rules –Roll two dice 7 or 11 on first throw, player wins 2, 3, or 12 on first throw, player loses 4, 5, 6, 8, 9, 10 –value becomes player's "point" –player must roll his point before rolling 7 to win

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ rollDice prototype 1.1 Initialize variables and enum 1.2 Seed srand 2. Define switch statement for win/loss/continue 1// Fig. 3.10: fig03_10.cpp 2// Craps 3#include 4 5using std::cout; 6using std::endl; 7 8#include 9 10#include 11 12using std::time; 13 14int rollDice( void ); // function prototype 15 16int main() 17{ 18 enum Status { CONTINUE, WON, LOST }; 19 int sum, myPoint; 20 Status gameStatus; srand( time( 0 ) ); 23 sum = rollDice(); // first roll of the dice switch ( sum ) { 26 case 7: 27 case 11: // win on first roll 28 gameStatus = WON; 29 break; 30 case 2: 31 case 3: 32 case 12: // lose on first roll 33 gameStatus = LOST; 34 break; Notice how the enum is defined

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Define loop to continue playing 2.2 Print win/loss 35 default: // remember point 36 gameStatus = CONTINUE; 37 myPoint = sum; 38 cout << "Point is " << myPoint << endl; 39 break; // optional 40 } while ( gameStatus == CONTINUE ) { // keep rolling 43 sum = rollDice(); if ( sum == myPoint ) // win by making point 46 gameStatus = WON; 47 else if ( sum == 7 ) // lose by rolling 7 49 gameStatus = LOST; 50 } if ( gameStatus == WON ) 53 cout << "Player wins" << endl; 54 else 55 cout << "Player loses" << endl; return 0; 58} 59

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Define rollDice function Program Output Player rolled = 11 Player wins Player rolled = 11 Player wins Player rolled = 10 Point is 10 Player rolled = 6 Player rolled = 11 Player rolled = 6 Player rolled = 10 Player wins Player rolled = 4 Point is 4 Player rolled = 5 Player rolled = 9 Player rolled = 10 Player rolled = 9 Player rolled = 3 Player rolled = 7 Player loses 60int rollDice( void ) 61{ 62 int die1, die2, workSum; die1 = 1 + rand() % 6; 65 die2 = 1 + rand() % 6; 66 workSum = die1 + die2; 67 cout << "Player rolled " << die1 << " + " << die2 68 << " = " << workSum << endl; return workSum; 71}

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Storage Classes Variables have attributes –Name, Type, Size, Value Identifier are name given to variables and user defined functions Identifiers also have other attributes –Storage class specifier –Scope –Linkage

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Storage Classes Storage class specifiers - Instructions to the compiler, on how a variable should be stored –Storage class Duration during which the identifier exists in memory Some are created and destroyed Some remain in memory throughout the execution of main Two storage classes (category), automatic or static –Scope Where object is referenced in program –Linkage Where an identifier is known (current source file or external file) C++ supports 5 specifiers –auto, extern, register, static, mutable

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Storage Classes extern –used to signify a reference to a global variable whose storage is allocated elsewhere (other file). –Default for global variables and functions. –Known in any function

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Storage Classes static –Local variables defined in functions –Keep value after function ends –Only known in their own function –Variables exist for entire program execution –Only initialized once, when created

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Storage Classes static –Different meanings for local and global vars. –static local variable Makes a variable permanent similar to global variable, but static variables are only visible to functions they belong to. For local var in a function, value of the variable is saved when the function ends and is restored when the function is restarted. Initialized once, at program startup. –static global variable When applied to a global var, it is visible only to the functions that belong in the same file. It is invisible to functions in other files, which may be part of the same program. mutable –used within classes. Allows const variables to be modified by const functions. We will not cover this.

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Identifier Scope Rules File scope –Defined outside a function, known in all functions –Examples include, global variables, function definitions and functions prototypes Function scope –Can only be referenced inside a function body –Only labels ( start:, case:, etc.) and local variables Block scope –Declared inside a block. Begins at declaration, ends at } –Variables, function parameters (local variables of function) –Outer blocks “hidden” from inner blocks if same variable name Function prototype scope –Identifiers in parameter list –Names in function prototype optional, only type is required

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Function prototypes 1.1 Initialize global variable 1.2 Initialize local variable 1.3 Initialize local variable in block 2. Call functions 3. Output results 1// Fig. 3.12: fig03_12.cpp 2// A scoping example 3#include 4 5using std::cout; 6using std::endl; 7 8void a( void ); // function prototype 9void b( void ); // function prototype 10void c( void ); // function prototype 11 12int x = 1; // global variable 13 14int main() 15{ 16 int x = 5; // local variable to main cout << "local x in outer scope of main is " << x << endl; { // start new scope 21 int x = 7; cout << "local x in inner scope of main is " << x << endl; 24 } // end new scope cout << "local x in outer scope of main is " << x << endl; a(); // a has automatic local x 29 b(); // b has static local x 30 c(); // c uses global x 31 a(); // a reinitializes automatic local x 32 b(); // static local x retains its previous value 33 c(); // global x also retains its value 34 x is different inside and outside the block. local x in outer scope of main is 5 local x in inner scope of main is 7 local x in outer scope of main is 5

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Define Functions 35 cout << "local x in main is " << x << endl; return 0; 38} 40void a( void ) 41{ 42 int x = 25; // initialized each time a is called cout << endl << "local x in a is " << x 45 << " after entering a" << endl; 46 ++x; 47 cout << "local x in a is " << x 48 << " before exiting a" << endl; 49} 51void b( void ) 52{ 53 static int x = 50; // Static initialization only 54 // first time b is called. 55 cout << endl << "local static x is " << x 56 << " on entering b" << endl; 57 ++x; 58 cout << "local static x is " << x 59 << " on exiting b" << endl; 60} 62void c( void ) 63{ 64 cout << endl << "global x is " << x 65 << " on entering c" << endl; 66 x *= 10; 67 cout << "global x is " << x << " on exiting c" << endl; 68} Local automatic variables are created and destroyed each time a is called. Local static variables are not destroyed when the function ends. Global variables are always accessible. Function c references the global x. local x in a is 25 after entering a local x in a is 26 before exiting a local static x is 50 on entering b local static x is 51 on exiting b global x is 1 on entering c global x is 10 on exiting c

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Program Output local x in outer scope of main is 5 local x in inner scope of main is 7 local x in outer scope of main is 5 local x in a is 25 after entering a local x in a is 26 before exiting a local static x is 50 on entering b local static x is 51 on exiting b global x is 1 on entering c global x is 10 on exiting c local x in a is 25 after entering a local x in a is 26 before exiting a local static x is 51 on entering b local static x is 52 on exiting b global x is 10 on entering c global x is 100 on exiting c local x in main is 5

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 43 RecursionRecursion Recursive functions –Are functions that calls themselves –Can only solve a base case –If not base case, the function breaks the problem into a slightly smaller, slightly simpler, problem that resembles the original problem and Launches a new copy of itself to work on the smaller problem, slowly converging towards the base case Makes a call to itself inside the return statement –Eventually the base case gets solved and then that value works its way back up to solve the whole problem

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 44 RecursionRecursion Example: factorial n! = n * ( n – 1 ) * ( n – 2 ) * … * 1 –Recursive relationship ( n! = n * ( n – 1 )! ) 5! = 5 * 4! 4! = 4 * 3!… –Base case (1! = 0! = 1) // Recursive definition of function factorial unsigned long factorial( unsigned long number ) { if ( number <= 1 ) // base case return 1; else // recursive case return number * factorial( number - 1 ); }

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 45 RecursionRecursion unsigned long factorial( unsigned long number ){ if ( number <= 1 ) return 1; else return number * factorial( number - 1 ); } Anytime a function is called, all current information is saved on the stack, the function is executed and then program starts execution immediately after the function call int j = factorial(4) return (4 * factorial(3) ) return (3 * factorial(2) ) return (2 * (factorial(1) ) Return value = 2 2*factorial(1) = 2 * 1 = 2 Return value = 24 4*factorial(3) = 4 * 6 = 24 Return value = 6 3*factorial(2) = 3 * 2 = 6 Return value = 1 factorial(1) = 1

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Example Using Recursion: The Fibonacci Series Fibonacci series: 0, 1, 1, 2, 3, 5, 8... –Each number sum of two previous ones –Example of a recursive formula: fib(n) = fib(n-1) + fib(n-2) C++ code for fibonacci function long fibonacci( long n ) { if ( n == 0 || n == 1 ) // base case return n; else return fibonacci( n - 1 ) + fibonacci( n – 2 ); }

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Example Using Recursion: The Fibonacci Series Diagram of Fibonnaci function f( 3 ) f( 1 ) f( 2 ) f( 1 )f( 0 )return 1 return 0 return + +

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Function prototype 1.1 Initialize variables 2. Input an integer 2.1 Call function fibonacci 2.2 Output results. 3. Define fibonacci recursively 1// Fig. 3.15: fig03_15.cpp 2// Recursive fibonacci function 3#include 5using std::cout; 6using std::cin; 7using std::endl; 8 9unsigned long fibonacci( unsigned long ); 10 11int main() 12{ 13 unsigned long result, number; cout << "Enter an integer: "; 16 cin >> number; 17 result = fibonacci( number ); 18 cout << "Fibonacci(" << number << ") = " << result << endl; 19 return 0; 20} 21 22// Recursive definition of function fibonacci 23unsigned long fibonacci( unsigned long n ) 24{ 25 if ( n == 0 || n == 1 ) // base case 26 return n; 27 else // recursive case 28 return fibonacci( n - 1 ) + fibonacci( n - 2 ); 29} Only the base cases return values. All other cases call the fibonacci function again.

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Program Output Enter an integer: 0 Fibonacci(0) = 0 Enter an integer: 1 Fibonacci(1) = 1 Enter an integer: 2 Fibonacci(2) = 1 Enter an integer: 3 Fibonacci(3) = 2 Enter an integer: 4 Fibonacci(4) = 3 Enter an integer: 5 Fibonacci(5) = 5 Enter an integer: 6 Fibonacci(6) = 8 Enter an integer: 10 Fibonacci(10) = 55 Enter an integer: 20 Fibonacci(20) = 6765 Enter an integer: 30 Fibonacci(30) = Enter an integer: 35 Fibonacci(35) =

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf 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) Recursion can be expensive in term of resources. Every time a function calls itself, all the data of the calling function is saved and a new copy of all the variables is created.

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Functions with Empty Parameter Lists Empty parameter lists –Either writing void or leaving a parameter list empty indicates that the function takes no arguments void print(); or void print( void ); –Function print takes no arguments and returns no value print();Takes no arguments and returns int (default return type is int)

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Function prototypes (take no arguments) 2. Call the functions 3. Function definitions Program Output 1// Fig. 3.18: fig03_18.cpp 2// Functions that take no arguments 3#include 4 5using std::cout; 6using std::endl; 7 8void function1(); 9void function2( void ); 10 11int main() 12{ 13 function1(); 14 function2(); return 0; 17} 18 19void function1() 20{ 21 cout << "function1 takes no arguments" << endl; 22} 23 24void function2( void ) 25{ 26 cout << "function2 also takes no arguments" << endl; 27} function1 takes no arguments function2 also takes no arguments Notice the two ways of declaring no arguments.

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Inline Functions inline functions –Reduce function-call overhead –Asks the compiler to copy code into program instead of using a function call –Compiler can ignore inline –Should be used with small, often-used functions Example: inline double cube( const double s ) { return s * s * s; }

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf References and Reference Parameters Call by value –Copy of data passed to function –Changes to copy do not change original –Used to prevent unwanted side effects Call by reference –Function can directly access data –Changes affect original Reference parameter alias for argument –& is used to signify a reference void change( int &variable ) { variable += 3; } –Adds 3 to the variable inputted int y = &x. –A change to y will now affect x as well

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Function prototypes 1.1 Initialize variables 2. Print x 2.1 Call function and print x 2.2 Print z 2.3 Call function and print z 3. Function Definition of squareByValue Notice the use of the & operator 1// Fig. 3.20: fig03_20.cpp 2// Comparing call-by-value and call-by-reference 3// with references. 4#include 6using std::cout; 7using std::endl; 8 9int squareByValue( int ); 10void squareByReference( int & ); 11 12int main() 13{ 14 int x = 2, z = 4; cout << "x = " << x << " before squareByValue\n" 17 << "Value returned by squareByValue: " 18 << squareByValue( x ) << endl 19 << "x = " << x << " after squareByValue\n" << endl; 2 21cout<<"z = " << z << " before squareByReference" << endl; 22 squareByReference( z ); 23cout<<"z = " << z << " after squareByReference" << endl; return 0; 26} 29{ 30 return a *= a; // caller's argument not modified 31} 28int squareByValue( int a )

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Function Definition of squareByReference Program Output x = 2 before squareByValue Value returned by squareByValue: 4 x = 2 after squareByValue z = 4 before squareByReference z = 16 after squareByReference 32 33void squareByReference( int &cRef ) 34{ 35 cRef *= cRef; //caller's argument modified 36}

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Function swap Uses to arguments that are passed by reference #include void swap (int &x, int &y); main () { int a = 1, b = 2; swap (a, b); return ; } void swap (int &x, int &y) { int temp = x; x = y; y = temp; }

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Default Arguments If function parameter is omitted, gets default value –Can be constants, global variables, or function calls –Must be the rightmost argument(s ) –Default values only specified in the prototype of the function Set defaults in function prototype int defaultFunction( int x = 1, int y = 2, int z = 3 ); Set defaults in function prototype int defaultFunction( int x = 1, int y = 2, int z = 3 );

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Function prototype 2. Print default volume 2.1 Print volume with one parameter 2.2 Print with 2 parameters 2.3 Print with all parameters. 3. Function definition 1// Fig. 3.23: fig03_23.cpp 2// Using default arguments 3#include 4 5using std::cout; 6using std::endl; 7 8int boxVolume( int length = 1, int width = 1, 9 int height = 1 ); 10int main() 11{ 12 cout << "The default box volume is: " << boxVolume() 13 << "\n\nThe volume of a box with length 10,\n" 14 << "width 1 and height 1 is: " << boxVolume( 10 ) 15 << "\n\nThe volume of a box with length 10,\n" 16 << "width 5 and height 1 is: " << boxVolume( 10, 5) 17 << "\n\nThe volume of a box with length 10,\n" 18 << "width 5 and height 2 is: " << boxVolume( 10, 5, 2 ) 19 << endl; return 0; 22} 23 24// Calculate the volume of a box 25int boxVolume( int length, int width, int height ) 26{ 27 return length * width * height; 28}

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Program Output The default box volume is: 1 The volume of a box with length 10, width 1 and height 1 is: 10 The volume of a box with length 10, width 5 and height 1 is: 50 The volume of a box with length 10, width 5 and height 2 is: 100 Notice how the rightmost values are defaulted.

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Unary Scope Resolution Operator Unary scope resolution operator ( :: ) –Access global variables if a local variable has same name –not needed if names are different –instead of variable use ::variable

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Define variables 2. Print variables Program Output 1// Fig. 3.24: fig03_24.cpp 2// Using the unary scope resolution operator 3#include 4 5using std::cout; 6using std::endl; 7 8#include 9 10using std::setprecision; 11 12const double PI = ; 13 14int main() 15{ 16 const float PI = static_cast ( ::PI ); cout << setprecision( 20 ) 19 << " Local float value of PI = " << PI 20 << "\nGlobal double value of PI = " << ::PI << endl; return 0; 23} Local float value of PI = Global double value of PI = Notice the use of ::

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Function Overloading Function overloading –Having functions with same name and different parameters –Should perform similar tasks i.e., a function to square int s, and function to square float s, (but doesn’t have to). int square( int x) {return x * x;} float square(float x) { return x * x; } –Program chooses function by signature signature determined by function name and parameter types –Can have the same return types

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Define overloaded function 2. Call function Program Output 1// Fig. 3.25: fig03_25.cpp 2// Using overloaded functions 3#include 4 5using std::cout; 6using std::endl; 7 8int square( int x ) { return x * x; } 9 10double square( double y ) { return y * y; } 11 12int main() 13{ 14 cout << "The square of integer 7 is " << square(7 ) 15 << "\nThe square of double 7.5 is " << square(7.5) 16 << endl; return 0; 19} The square of integer 7 is 49 The square of double 7.5 is Functions have same name but different parameters

 2000 Prentice Hall, Inc. All rights reserved.  2001 NHTI CP 107 M. Saleem Yusuf Function Templates Function templates –Compact way to make overloaded functions –Keyword template –Keyword class or typename before every formal type parameter (built in or user defined) template T square( T value1 ) { return value1 * value1; } –T replaced by type parameter in function call. int x; int y = square(x); If int, all T 's become int s Can use float, double, long...

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Define overloaded function 2. Call function Program Output Square of 2 = 4 Square of = Square of 22 = 484 #include using namespace std; template T Square( T value1 ); void main(void) { int i = 2; double j = 33.33; float k = 22.0F; cout << "Square of " << i << " = " << Square(i) << endl; cout << "Square of " << j << " = " << Square(j) << endl; cout << "Square of " << k << " = " << Square(k) << endl << endl; } template T Square( T value1 ) { return value1 * value1; }

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ #include using namespace std; template bool IsEqual( T value1, T value2 ); void main(void) { char ch_a = 'a'; char ch_b = 'b'; int iNum1 = 100; int iNum2 = 1000; cout << "ch_a is equal to ch_b " << ( IsEqual(ch_a, ch_b) ? "True" : "False") << endl; cout << "ch_a is equal to ch_b " << ( IsEqual(ch_b, ch_b) ? "True" : "False") << endl; if (IsEqual(iNum1, iNum2)) cout << "numbers are equal " << endl; else cout << "numbers are NOT equal " << endl; cout << "24 is equal to 24 " << ( IsEqual(24, 24) ? "True" : "False") << endl; } template bool IsEqual( T value1, T value2 ) { if (value1 == value2) return 1; else return 0; } ch_a is equal to ch_b False ch_a is equal to ch_b True numbers are NOT equal 24 is equal to 24 True

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 M. Saleem Yusuf modified 2/17/ Power (2, 0) = 1 Power (2, 1) = 2 Power (2.45, 2) = #include using namespace std; template T Power( T base, U exponent ); void main(void) { cout << "Power (2, 0) = " << Power(2.0, 0) << endl; cout << "Power (2, 1) = " << Power(2.0, 1) << endl; cout << "Power (2.45, 2) = " << Power(2.45, 2) << endl; } template T Power( T base, U exponent ) { int i; T j = base; if (exponent == 0) return 1; else if (exponent == 1) return base; else { for (i = 1; i < exponent ; i++) base = base * j; } return base; }