Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6: Functions.

Similar presentations


Presentation on theme: "Chapter 6: Functions."— Presentation transcript:

1 Chapter 6: Functions

2 Outline What is “Function” Sending data into function
The return statement Local and Global variables

3 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection of statements to perform a task Motivation for modular programming: Improves maintainability of programs Simplifies the process of writing programs In summary: Modular programs are easier to develop, modify and maintain than programs constructed otherwise

4

5 main() – driver function
To provide for the orderly placement and execution of functions, each C++ program must have one and only one function named main(). The main() function is referred to as a driver function because it directs or "drives" the other modules or functions in the order in which they are to be executed

6 Defining and Calling Functions
Function definition: statements that make up a function Function call: statement causes a function to execute

7 Function Definition Definition includes:
return type: data type of the value that function returns to the part of the program that called it name: name of the function. Function names follow same rules as variables parameter list: variables containing values passed to the function body: statements that perform the function’s task, enclosed in {}

8 Function Definition

9 Function Return Type If a function returns a value, the type of the value must be indicated: int main() If a function does not return a value, its return type is void: void printHeading() { cout << "Monthly Sales\n"; }

10 Function Return Type The return statement can then be eliminated from the main ( ) function. The structure of main( ) can be as follows: void main( ) { //program statements go here; }

11

12

13 Function example #include<iostream> using namespace std; /********************* //define a function * *********************/ void display_message() { cout<< "Hello from the function displaymessage.\n"; } //main function * void main() cout<<"hello world!! from main function.\n"; display_message();

14

15 Calling a Function void printHeading() {
cout << "Monthly Sales\n"; } To call a function, use the function name followed by ()and ; printHeading(); When called, program executes the body of the called function After the function terminates, execution resumes in the calling function at point of call.

16 Calling Functions main can call any number of functions
Functions can call other functions Compiler must know the following about a function before it is called: name return type number of parameters data type of each parameter

17 Function Prototypes Ways to notify the compiler about a function before a call to the function: Place function definition before calling function’s definition or 2. Use a function prototype (function declaration) – like the function definition without the body Header: void printHeading() Prototype: void printHeading();

18 (Program Continues)

19

20 Prototype Notes Place prototypes near top of program
Program must include either prototype or full function definition before any call to the function – compiler error otherwise When using prototypes, can place function definitions in any order in source file

21 Outline What is “Function” Sending data into function
The return statement Local and Global variables

22 Sending Data into a Function
Can pass values into a function at time of call: displayValue(5); // function call Values (data) passed to function are arguments Variables in a function that hold the values passed as arguments are parameters void displayValue(int num) { cout << "The value is " << num << endl; } The integer variable num is a parameter. It accepts any integer value passed to the function.

23 What is the output?

24 The function call in line 11 passes the value 5
as an argument to the function.

25 Parameters, Prototypes, and Function Headers
For each function argument, the prototype must include the data type of each parameter inside its parentheses the header must include a declaration for each parameter in its () void evenOrOdd(int); //prototype void evenOrOdd(int num) //header evenOrOdd(val); //call

26 Passing Multiple Arguments
When calling a function and passing multiple arguments: the number of arguments in the call must match the prototype and definition the first argument will be used to initialize the first parameter, the second argument to initialize the second parameter, etc.

27

28 The function call in line 18 passes value1, value2, and value3 as arguments to the function.

29 Passing Data by Value Pass by value: when an argument is passed to a function, its value is copied into the parameter. Changes to the parameter in the function do not affect the value of the argument

30 Passing Data by Value 5 val num Example: int val=5; evenOrOdd(val);
int evenOrOdd (int num) { … num = num+10; …} evenOrOdd can change variable num, but it will have no effect on variable val 5 val argument in calling function num parameter in evenOrOdd function

31 Outline What is “Function” Sending data into function
The return statement Local and Global variables

32 The return Statement The RETURN statement has two purposes:
The return statement causes a function to END immediately A function may send ONE value back to the part of the program that called the function

33 The return Statement Used to end execution of a function
Can be placed anywhere in a function Statements that follow the return statement will not be executed Can be used to prevent abnormal termination of program In a void function without a return statement, the function ends at its last }

34 (Program Continues)

35 Program 6-11(Continued)

36 Returning a Value From a Function
A function can return a value back to the statement that called the function. A function returning a value must specify, in its header line, the data type of the value that will be returned. In a value-returning function, the return statement can be used to return a value from function to the point of call. Example: int sum(int num1, int num2) { int result; result = num1 + num2; return result; }

37 A Value-Returning Function
Return Type – Incorrect int sum(int num1, int num2) { double result; result = num1 + num2; return result; } Value Being Returned

38 A Value-Returning Function
Return Type – Correction – Depending on design of code double sum(int num1, int num2) { double result; result = num1 + num2; return result; } Value Being Returned

39 A Value-Returning Function
Return Type – Correction – Depending on design of code int sum(int num1, int num2) { int result; result = num1 + num2; return result; } Value Being Returned Failure to match the return value exactly with the function's declared data type may not result in an error when the program is compiled, but it may lead to undesired results because the return value is always converted to the data type declared in the function declaration

40 Calling function to receive the value
On the receiving side, the called function must: be alerted to the type of value to expect properly use the returned value provide a variable to store the value accomplished by using a standard assignment statement, e.g.: total = sum (firstnum, secondnum); use the value directly in an expression, e.g.: cout << sum(firstnum, secondnum); The next program illustrates the inclusion of both the prototype and assignment statements for main( ) to correctly call and store a returned value from sum( ).

41 int findSum(int, int); //the function prototype
int main ( void ) { int firstnum, secondnum, total; cout << "Please enter your first number to be added: "; cin >> firstnum; cout << "Good Job!! Please enter your second number to be added: "; cin >> secondnum; total = findSum(firstnum, secondnum); //the function is called here cout << "The sum of the two numbers you have entered is " << total; return 0; } int findSum(int number1, int number2) //function header line { //start of function body int sum; //variable declaration sum = number1 + number2; //calculates the sum return sum; //return statement

42 In reviewing the previous program, it is important to note the four items we have introduced:
The first item is the prototype for findSum( ). This statement, which ends with a semicolon, alerts main( ) and any other functions that use findSum( ), what data type findSum( ) will be returning and what data types values findSum( ) will be expecting to receive. The next item is the use of an assignment statement to store the returned value from the findSum( ) call into the variable total. Make sure to declare total correctly within main( )'s declaration statements so that it matches the data type of the returned value.

43 In reviewing the previous program, it is important to note the four items we have introduced:
3. When coding the findSum( ), make sure the first line (function header line) declares that the function will return the same data type that was listed in the function prototype. 4. Make sure the expression in the return statement in findSum( ) evaluates to the same data type declared as the return data type.

44 //function prototypes
double inputFahrenheit( ); //reads fahrenheit temp from user double convertFahenheitToCelsius(double); //converts fahren temp to celsius void displayConvertedDegree (double, double); //displays converted temperature int main ( void ) { //Declaration statements double fahrenheit = 0.0; //stores the temp in fahren entered by user double celsius = 0.0; //stores the calculated converted temp in celsius fahrenheit = inputFahrenheit( ); //function call to get data from user celsius = convertFahenheitToCelsius(fahrenheit);//function call-convert F˚ to celsius displayConvertedDegree(celsius, fahrenheit); //function call -display converted temp return 0; } /* This function allows the user to input the temperature in Fahrenheit that is to be converted to Celsius */ double inputFahrenheit( ) double f; cout << "Please enter the temperature recorded in Fahreheit " << endl << "that you wish to be converted to Celsius: "; cin >> f; return f; /* This function converts Fahrenheit to Celsius */ double convertFahenheitToCelsius(double f_degrees) { return (5.0 / 9.0 ) * ( f_degrees ); } /*This function displays Celsius equivalent of the temperture that was entered in Fahrenheit */ void displayConvertedDegree(double cel, double fahren) { cout << fahren << " Fahrenheit is " << cel << " Celsius. " << endl;}

45 Please enter the temperature recorded in Fahreheit
Output: Please enter the temperature recorded in Fahreheit that you wish to be converted to Celsius: 32 32 Fahrenheit is 0 Celsius. This program consists of 4 functions main( ) inputFahrenheitToCelsius( ) convertFahrenheitToCelsius( ) displayConvertedDegree( )

46 The main( ) is the driver function. It calls the other three functions
The main( ) is the driver function. It calls the other three functions. These three called functions must be declared to main( ) by means of a function prototype. The prototype for inputFahrenheitToCelsius( ) specifies that this function will return a double-precision number and accept nothing for input. The prototype for convertFahrenheitToCelsius( ) specifies that the function will return a double-precision number and accept a double-precision number for input. The prototype for displayConvertedDegree( ) specifies that it will return nothing and accept two double-precision numbers as input to the function.

47 The function call statements are in the body of main( )
The function call statements are in the body of main( ). When the inputFahrenheit( ) is called, it sends no values to the function for input but stores the returned value from the function into the variable fahrenheit in main( ). When convertFahrenheitToCelsius( ) is called from main( ), it sends a copy of the value stored in the variable fahrenheit in main( ) and stores the value returned from this function in a variable named celsius in main( ). When the displayConvertedDegree( ) function is called from main( ), it sends a copy of the values stored in celsius and fahrenheit as input and returns nothing.

48 Returning a Value From a Function
The prototype and the definition must indicate the data type of return value (not void) Calling function should use return value: assign it to a variable send it to cout use it in an expression

49 Outline What is “Function” Sending data into function
The return statement Local and Global variables

50 Local Variables Variables defined inside a function are local to that function. They are hidden from the statements in other functions, which normally cannot access them. Because the variables defined in a function are hidden, other functions may have separate, distinct variables with the same name.

51 Local Variables A function can be thought of as a closed box, with slots at the top to receive values and a single slot at the bottom of the box to return a value . The metaphor of a closed box is useful because it emphasizes the fact that what goes on inside the function, including all variable declarations within the function's body, is hidden from the view of all other functions.

52 Local Variables

53 When the program is executing in main, the num variable defined in main is visible. When anotherFunction is called, however, only variables defined inside it are visible, so the num variable in main is hidden.

54 Local Variable Lifetime
A function’s local variables exist only while the function is executing. A local variable is any variable declared inside a function in a program. When the function begins, its local variables and its parameter variables are created in memory, and when the function ends, the local variables and parameter variables are destroyed. This means that any value stored in a local variable is lost between calls to the function in which the variable is declared.

55 Global Variables A global variable is any variable defined outside all the functions in a program. The scope of a global variable is the portion of the program from the variable definition to the end. This means that a global variable can be accessed by all functions that are defined after the global variable is defined. Constant variable is a good example for global variable

56 Global Variables You should avoid using global variables because they make programs difficult to debug. Global variables allow the programmer to "jump around" the normal safeguards provided by functions. Rather than passing variables to a function, it is possible to make all variables global ones. DO NOT DO THIS. By making all variables global, you instantly destroy the safeguards that C++ provides to make functions independent and insulated from each other, including the necessity of carefully designating the type of parameters a function needs, the variables used in the function, and the value returned. Using only global variables can be especially disastrous in larger programs that have many functions. A global variable can be accessed and changed by any function following the global declaration which makes it time-consuming and frustrating to locate the origin of an erroneous value in a large program

57 Global Constants Global constants defined for values that do not change throughout the program’s execution.

58 The constants are then used for those values throughout the program.

59 Summary : Local and Global Variables
Every variable in a program has a scope, which determines where in the program the variable can be used. The scope of a variable is either local or global and is determined by where the variable's definition statement is placed. A local variable is defined within a function and can be used only within its defining function or block. A global variable is defined outside a function and can be used in any function following the variable's definition.


Download ppt "Chapter 6: Functions."

Similar presentations


Ads by Google