1 / 44

Chapter 6: Functions

Chapter 6: Functions. Outline. What is “Function” Sending data into function The return statement Local and Global variables. Modular Programming. Modular programming : breaking a program up into smaller, manageable functions or modules

morna
Download Presentation

Chapter 6: Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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. 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

  5. Function Definition

  6. 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: voidprintHeading() { cout << "Monthly Sales\n"; }

  7. 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; }

  8. 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(); }

  9. Calling a Function voidprintHeading() { 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.

  10. 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();

  11. (Program Continues)

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

  13. 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.

  14. What is the output?

  15. Slide 6- 24

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

  17. 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

  18. 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.

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

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

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

  22. 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

  23. 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 }

  24. (Program Continues)

  25. Program 6-11(Continued)

  26. 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;}

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

  28. 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

  29. 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

  30. 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.: 2 * sum (firstnum, secondnum); 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( ).

  31. intfindSum(int, int); //the function prototype int main ( void ) { intfirstnum, 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; } intfindSum(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 }

  32. //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 - 32.0 ); } /*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;}

  33. 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( )

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

  35. Local Variables

  36. 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.

  37. 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

  38. 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

More Related