Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.

37
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 1 March 25, 2022

Transcript of Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.

Structure ProgrammingLecture 8

Chapter 5&6 - Function – part I

1April 18, 2023

Outlines

2

• Introduction• Math Library Functions• Function Definitions with Multiple Parameters• Return values• Argument Passing• Declaration, definitions and calling of user-

defined functions• Functions with no type• functions with Empty Parameter List

April 18, 2023

Introduction

• Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces, or components.

– This technique is called divide and conquer.– Any sequence of instructions that appears in a program more than once

can be encapsulated into a function.

• In C++ we will have two types of functions:• Pre-defined “such as functions in the class math ‘Cmath’ ”.

• User/programmer defined

• Another reason to use functions (and the reason they were invented, long ago) is to reduce program size.

3April 18, 2023

Program Components in C++• The C++ Standard Library provides a rich collection

of functions.• Functions you write are referred to as user-defined

functions or programmer-defined functions.

• A function is invokedinvoked by a function callfunction call, and when the called function completes its task,– either returns a result or

– simply returns control to the caller. ”if it is void return value”4April 18, 2023

Program Components in C++

• The function’s code is stored in only one place in memory, even though the function is executed many times in the program.

Math Library Functions

• Function prototypes for global functions global functions are placed in header header filesfiles, so that the global functions can be reused in any program that includes the header file and that can link to the function’s object code.

• The <cmath><cmath> header file provides a collection of functions that enable you to perform common mathematical calculations.

• All functions in the <cmath> is called simply by specifying the name of the function followed by parentheses containing the function’s arguments.

cos (x)• Some math library functions are summarized in Fig. 6.2.

– In the figure, the variables x and y are of type double.

6April 18, 2023

7April 18, 2023

8April 18, 2023

Function Declarations vs. DefinitionsExample

Int add(int x, int y); // Declaration (or prototype)

. . .

Void main()

{

. . .

cout << x << “! is “ << add(x,y) << endl; // calling the function

. . .

}

. . .

Int add(int x, int y) // Definition

{

. . .

} 9

Before a function may be called by any other function it must be either defined or declared.

April 18, 2023

10April 18, 2023

Function Components

11April 18, 2023

Function Declarations vs. Definitions, cont.

• The compiler refers to the function prototype to check that calls to function contain – the correct numbers and types of arguments

– and that the types of the arguments are in the correct order.

• Each argument must be consistent with the type of the corresponding parameter.

• If the arguments passed to a function do not match the types specified in the function’s prototype, the compiler attempts to convert the arguments to those types.

12April 18, 2023

Example 2, cont.

#include <iostream>

long factorial(int); // declaration

Void main()

{ int x;

cout << “Please enter a number> “ << endl;

cin >> x;

cout << x << “! is “ << factorial(x) << endl;}

How might we call our function from a main() function?

When a function is declared separately from its definition, this is called a forward declaration. Forward declarations need only to specify return type, parameters type, parameter number and order of parameters. Parameter names are irrelevant. 13April 18, 2023

Example 2, cont.

The definition consists of a line called the declarator, followed by the function body.

The definition contains the actual code for the function.

long factorial(int n) // declarator{

long result = 1, k = n; // function body. while(k > 1)

{

result *= k--; }

return result;

}

14April 18, 2023

Function with no return results

• If the function does return a result, the statement

return expression;

• If the function does not return a result (i.e., it has a void return type), control returns when the program reaches the function-ending right brace,

or by execution of the statement

return;

15April 18, 2023

Functions with no return results. The use of void

// void function example#include <iostream>using namespace std;void printmessage (int x){ for (int i=0; i<=x; i++)

cout << "I'm a function!“<< x ;}void main (){

printmessage (5);}

16April 18, 2023

Function Definitions with Multiple Parameters

• A function is a group of statements that is executed when it is calledcalled from some point of the program.

• Function format with multiple parameters :ReturnType funcName ( parameter1, parameter2, ...)

{ statements }• Multiple parameters are specified in both the function prototype and the

function header as a comma-separated list.

• Function with no parameters is specified by writing either void or nothing at all in parentheses.

ReturnType funcName ( ) or ReturnType funcName (void)

17April 18, 2023

April 18, 2023 18

  Function Definitions with Multiple Parameters, cont.

{ code to perform a task }ReturnType funcName (parameters)

---- ;Var = funcName (arguments); //function call---;

19

• There must be one argument in the function call function call for each parameter in the function definition.• Arguments is the name of the values that the function call passes to the function for the parameters.April 18, 2023

Example

#include <iostream>using namespace std;

int addition (int a, int b){

int r;r=a+b;return r;

}20April 18, 2023

int main (){

int z;z = addition (5,3);cout << "The result is " << z;return 0;

}The output of program:The result is 8

Example , cont.

21April 18, 2023

int main (){

int x=5, y=3, z;z = addition (5,3);cout << "The result is " << z << '\n';cout << "The second result is " << addition (5,3) << '\n';cout << "The third result is " << addition (x,y) << '\n';z= 4 + addition (x,y);cout << "The fourth result is " << z << '\n';return 0;

}

The result is 8The second result is 8The third result is 8The fourth result is 12

Example (some different calling methods), cont.

22April 18, 2023

Reference Parameters “Argument Passing” There are two ways to pass arguments to functions in C++:

Pass by VALUE Pass by REFERENCE

Pass by VALUE The value of a variable is passed along to the function The function creates copies of the argument passed to it. If the function modifies that value, the modifications stay within the

scope of that function and do not affect the original variable’s value in memory.

Pass by REFERENCE A reference to the variable is passed along to the function. The called function access the caller’s data directly. If the function modifies that value, the modifications appear also

within the scope of the calling function, i.e. The function can change the original variable’s value in memory.

23April 18, 2023

Argument Passing by Value

• Passing Constantsint z;z = addition (5,3);

• Passing Variablesint x=5, y=3, z;z= addition (x,y);

24April 18, 2023

25

Problem: i- What is the output of the following program?

void cubev(int );

void main( ){ int n=5; cout<< n<<endl; cubev( n); cout<< n<<endl;}

void cubev(int x){ x= x * x * x ;}

Call by Value Call by Value

April 18, 2023

Pass by VALUE

x5

cubev

5n

Main()

26

x125

cubev

5n

Main()

Start of the call

At the end of call

April 18, 2023

27

Problem: i- What is the output of the following program?

void cubev(int );

void main( ){ int n=5; cout<< n<<endl; cubev( n); cout<< n<<endl;}

void cubev(int x){ x= x * x * x ;}

5

5

Prob: ii - Modify this program to give the cube using Call by Reference?

Call by Value Call by Value

April 18, 2023

28

Solution: Cuber function using Call by Reference

void cuber(int &);

void main( ){ int n=5; cout<< n<<endl; cuber(n ); cout<< n<<endl;}

void cuber(int &x){

x= x * x * x ;}

5125

April 18, 2023

Pass by reference

5n

Main()

x

cuber

29

125n

Main()

x

cuber

Start of the call

At the end of call

April 18, 2023

Why use Pass By Reference?

Because you really want changes made to a parameter to persist in the scope of the calling function.

1. You need to return more than one value to the calling function.

2. Because you are passing a large amounts of data Passing by reference passes merely a reference

(pointer) to the data, not the data itself.

30April 18, 2023

Why use Pass By Reference?

1- Because you want to return two valuesvoid order (int & a, int & b){

if(a > b) { int temp = a; //swap them a = b; b = temp;

}}void main()

{ int num1 = 21, num2 = 12; //this pair not ordered order (num1, num2); cout << “num1 = “ << num1 << endl; cout << “num2 = “ << num2 << endl;

}31April 18, 2023

Pass by reference

21num1

Main()

12num2

a

b

order

12num1

Main()

21num2

a

b

order

32April 18, 2023

Your turn (1/4)• 3. Write a function called foo() that displays the word foo.

• 4. A one-statement description of a function is referred to as a function d_________ or a p_________.

• 5. The statements that carry out the work of the function constitute the function _________.

• 6. A program statement that invokes a function is a function _________.

• 7. The first line of a function definition is referred to as the _________. 33April 18, 2023

Your turn (2/4)• 8. A function argument is

a. a variable in the function that receives a value from the calling program.

b. a way that functions resist accepting the calling program’s values.

c. a value sent to the function by the calling program.d. a value returned by the function to the calling

program.

34April 18, 2023

Your turn (3/4)

• 13. How many values can be returned from a function?

• 14. True or false: When a function returns a value, the entire function call can appear on the right side of the equal sign and be assigned to another variable.

• 16. A function that doesn’t return anything has return type _________.

35April 18, 2023

Your turn (4/4)

• 17. Here’s a function:int times2(int a){return (a*2);}

Write a main() program that includes everything necessary to call this function.

36April 18, 2023

Answers 3. void foo()

{cout << “foo”;}

4. declaration, prototype5. body6. call7. declarator8. C13. one14. Ttrue16. Void17.

int times2(int a); // prototypemain(){int alpha = times2(37); // function call}