CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

22
CS102 Introduction to Computer Programming Chapter 6 Functions Continued

Transcript of CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

Page 1: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

CS102Introduction to Computer

ProgrammingChapter 6 Functions

Continued

Page 2: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

2

Chapter 6 Topics

• Storage Classes• Static Local Variables• Default Arguments• Using Reference Variables as Parameters• Inline Functions• Overloaded Functions• The exit() and atexit() Functions• Stubs and drivers• Testing Branches and Paths

Page 3: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

3

Storage Classes

• Four types of storage classesAutomatic Variables External Variables

Register Variables Static Variables

• All variables are assigned a default class– You can specify a variables storage class by

placing the class name before its data type– This will affect the variables lifetime not its

scope

Concept - All variables belong to a storage class, which determines the period of time the variable exists in memory.

Concept - All variables belong to a storage class, which determines the period of time the variable exists in memory.

Page 4: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

4

Static Variables

• Used to allow a local variable to remain in existence between function calls– makes the variable exist for the life time of the

program– a static variable is only initialized once, when it

is created

• static data_type value; ex. static int Num;

Concept - The variables stored in a functions local variables do not persist between function calls

Page 5: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

5

Program 6-20

/* This program shows that local variables do not retain their values between function calls. */

 #include <iostream.h>// Function prototypevoid ShowLocal(void);void main(void){

ShowLocal();ShowLocal();

}

/* Definition of function ShowLocal. The initial value of LocalNum, which is 5, is displayed. The value of LocalNum is then changed to 99 before the function returns.

*/ void ShowLocal(void){

int LocalNum = 5; // Local variablecout << "LocalNum is " << LocalNum << endl;LocalNum = 99;

}

Program Output

LocalNum is 5LocalNum is 5

Page 6: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

6

Program 6-21/* This program uses a static local

variable */#include <iostream.h>// Function prototype void ShowStatic(void);  void main(void){

for (int Count = 0; Count < 5; Count++)ShowStatic();

} // Definition of function ShowStatic.void ShowStatic(void){

static int StatNum = 0;cout << "StatNum is " << StatNum << endl;StatNum++;

}

StatNum is 0

Program Output

StatNum is 1

StatNum is 2

StatNum is 3

StatNum is 4

This program demonstrates the effect of defining a variable as static

Page 7: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

7

Default Arguments

• The value of a default argument must be a constant (a literal value or a named constant)

• When an argument is left out of a function call, all the arguments that come after it must be left out as well.

• If a function has a mixture of parameters, the parameters with default arguments must be declared last.

Concept - Default arguments are passed to parameters automatically if no argument is provided in the function call.

Concept - Default arguments are passed to parameters automatically if no argument is provided in the function call.

Page 8: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

8

Defining Default Arguments

• In the function prototypevoid showArea (float = 20, float = 10);

void showArea (float length = 20, float width = 10);

• In the function definitionvoid showArea (float length = 20, float width = 10)

float area = length * width;

cout << “the area is “ << area << endl:

Concept – If there is not function prototype the default arguments can be placed in the function definition

Concept – If there is not function prototype the default arguments can be placed in the function definition

Page 9: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

9

Program 6-23/* This program demonstrates default

function arguments. */ #include <iostream.h>// Function prototype with default arguments

*/void DisplayStars(int = 10, int = 1);void main(void){

DisplayStars();cout << endl;DisplayStars(5);cout << endl;DisplayStars(7, 3);

}/* Definition of function DisplayStars. The

default argument for Cols is 10 and for Rows is 1. This function displays a rectangle made of asterisks. */

void DisplayStars(int Cols, int Rows){

/* Nested loop. The outer loop controls the rows and the inner loop controls the columns. */for (int Down = 0; Down < Rows; Down++){

for (int Across = 0; Across < Cols; Across++)

cout << "*";cout << endl;

}}

Program Output

**********

*****

*********************

Page 10: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

10

Using Reference Variables as Parameters• A reference variable is an alias to another variable.

• Reference variables are declared with an & in front of the variable name

data_type &variable_name; ex. int &Num;

• Reference variables in function prototype statements, include the & after the data type

return_type function-name( data_type & );

ex. Void func ( int & );

Concept - Reference variables allow a function to access the parameters original argument and apply changes to it.

Concept - Reference variables allow a function to access the parameters original argument and apply changes to it.

Page 11: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

11

Program 6-24

/* This program uses a reference variable as a function parameter. */

 #include <iostream.h>/* Function prototype. The parameter is a

reference variable. */void DoubleNum(int &);void main(void){

int Value = 4;cout << "In main, Value is " << Value << endl;cout << "Now calling DoubleNum..." << endl;DoubleNum(Value);cout << "Now back in main. Value is " << Value << endl;

}

/* Definition of DoubleNum. The parameter RefVar is a reference variable. The value in RefVar is doubled. */

 

void DoubleNum (int &RefVar){

RefVar *= 2;}

Program Output

In main, Value is 4Now calling DoubleNum...

Now back in main. Value is 8

Reference Variable

Page 12: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

12

Program 6-25/* This program uses reference variables

as function parameters*/#include <iostream.h> /* Function prototypes. Both functions

use reference variables as parameters*/

void DoubleNum(int &);void GetNum(int &);void main(void){

int Value;GetNum(Value);DoubleNum(Value);cout << "That value doubled is " << Value << endl;

}

/* Definition of GetNum. The parameter UserNum is a reference variable. The user is asked to enter a number, which is stored in UserNum. */

 void GetNum(int &UserNum){

cout << "Enter a number: ";cin >> UserNum;

}/* Definition of DoubleNum. The parameter

RefVar is a reference variable. The value in RefVar is doubled. */

 void DoubleNum (int &RefVar){

RefVar *= 2;}

Program Output Enter a number: 12 [Enter]That value doubled is 24

Page 13: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

13

Reference Argument Warning

• Don’t get carried away with using reference variables as function parameters. Any time you allow a function to alter a variable that’s outside the function, you are creating potential debugging problems. Reference variables should only be used as parameters when the situation demands them.

Page 14: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

14

Overloaded Functions• C++ uses both the function name and the

parameter list to determine which function is being called.

• C++ will match the argument list of the function call with the parameter list of the functions defined and find a unique match.

Concept - Two or more functions may have the same name as long as their parameter lists are different.

Concept - Two or more functions may have the same name as long as their parameter lists are different.

Page 15: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

15

Program 6-26/* This program uses overloaded functions */#include <iostream.h>// Function prototypesint Square(int);float Square(float);void main(void){

int UserInt;float UserFloat;cout.precision(2);cout << "Enter an integer and a floating-point value: ";cin >> UserInt >> UserFloat;cout << "Here are their squares: ";cout << Square(UserInt) << " and " << Square(UserFloat);

}

*/ Definition of overloaded function Square. This function uses an int parameter, Number. It returns the square of Number as an int. */

 int Square(int Number){

return Number * Number;} /* Definition of overloaded function

Square. This function uses a float parameter, Number. It returns the square of Number as a float.*/

 float Square(float Number){

return Number * Number;}

Program Output

Enter an integer and floating-point value: 12 4.2 [Enter]Here are their squares: 144 and 17.64

Page 16: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

16

The exit and atexit Functions

• Must #include stdlib.h to use exit() and atexit function

• exit returns and integer: ex. exit(0);– this value is returned to the operating system that

your program is running within.– EXIT_FAILURE and EXIT_SUCCESS

• atexit registers a function to be called when the exit function is executed: ex. atexit(stop);

Concept - exit and atexit provides a mechanism for terminating a program while executing in a function.

Concept - exit and atexit provides a mechanism for terminating a program while executing in a function.

Page 17: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

17

Program 6-30/* This program shows how the

exit function causes a program to stop executing.*/

 #include <iostream.h>#include <stdlib.h> // For exit void Function(void); // Function

prototypevoid main(void){

Function();}

/* This function simply demonstrates that exit can be used to terminate a program from a function other than main. */

void Function(void)

{cout << "This program terminates with the exit function.\n";cout << "Bye!\n";exit(0);cout << "This message will never be displayed\n";cout << "because the program has already terminated.\n";

}

Program Output This program terminates with the exit function.Bye!

Page 18: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

18

Program 6-31/* This program demonstrates the exit

function. */#include <iostream.h>#include <stdlib.h> // For exit#include <ctype.h> // For touppervoid main(void){

char Response;cout << "This program terminates with the exit function.\n";cout << "Enter S to terminate with the EXIT_SUCCESS code\n";cout << "or F to terminate with the EXIT_FAILURE code: ";cin >> Response;switch (Response){case 's' : case 'S' :cout << "Exiting with EXIT_SUCCESS.\n"; exit(EXIT_SUCCESS);

case 'f' :

case 'F' : cout << "Exiting with EXIT_FAILURE.\n";

exit(EXIT_FAILURE);}

}Program Output This program terminates with the exit function.Enter S to terminate with the EXIT_SUCCESS codeor F to terminate with the EXIT_FAILURE code: s [Enter]Exiting with EXIT_SUCCESS.Program OutputThis program terminates with the exit function.Enter S to terminate with the EXIT_SUCCESS codeor F to terminate with the EXIT_FAILURE code: f [Enter]Exiting with EXIT_FAILURE.

Page 19: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

19

Stubs and Drivers

• A stub is a dummy function that can be quickly implemented and called in place of the real function

• A driver is program that tests a function by calling it with a range of test data passed in as arguments.

Concept – Stubs and Drivers are very helpful tools for testing and debugging programs that use functions

Concept – Stubs and Drivers are very helpful tools for testing and debugging programs that use functions

Page 20: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

20

Stubs

• Functionally decompose your program into individual algorithms and subroutines

• Write Stubs that allow your top level functions to continue executing– return static or typical values – Display debug messages– Simply return without doing anything

• Replace the stubs with the real functions when you have completed debugging the top level functions

Concept – Stubs allow you to focus on the logical flow of a program with out having to write all the code.

Concept – Stubs allow you to focus on the logical flow of a program with out having to write all the code.

Page 21: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

21

Stubs for Menu CallsSwitch (choice) {

case 1 : Adult (months);break;

case 2 : Child (months);break;

case 3 : Senior (months);break;

case 4 : exit(0);break;

default: cout <<"Enter a number";cout <<" between 1 - 4";

}

void Adult (int period){

cout << “You have called the Adult function”;

}void Adult (int period){

cout << “You have called the Child function”;

}void Adult (int period){

cout << “You have called the Senior function”;

}

Page 22: CS102 Introduction to Computer Programming Chapter 6 Functions Continued.

22

Drivers

• Develop the function based on the written specification

• Write a program that calls the function with various arguments as inputs– In range

– Out of range

– Exercise each path or branch

• Use the calling program to display the results

Concept – Drivers allow you to develop functions independent of the calling functions

Concept – Drivers allow you to develop functions independent of the calling functions