1. Trang chủ
  2. » Giáo án - Bài giảng

Lecture 7 functions tủ tài liệu training

12 36 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 12
Dung lượng 419,1 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Functions are invoked by a function call  A function call specifies the function name and provides information as arguments that the called function needs  Boss to worker analogy:  A

Trang 1

Lecture 7 - FUNCTIONS

 Functions perform a certain task as the name suggests

 Why use functions?

 The divide-and-conquer approach

 It makes program development more manageable by constructing programs from small, simple pieces

 Software reusability

 Using existing functions as building blocks to create new programs

 Avoids repeating code

 Dividing a program into meaningful functions makes the program easier to debug and maintain

 Any portion of the code that carries out a specific task or is to be repeated

several times can be converted into a function

 For example, the summing operation takes 2 inputs and returns their sum as output

 sum() function can be called every time to calculate the sum

Trang 2

Functions are invoked by a function call

 A function call specifies the function name and provides information (as arguments) that the called function needs

 Boss to worker analogy:

A boss (the calling function or caller) asks a worker (the called function) to perform a

task and return (i.e., report back) the results when the task is done

Function Definitions

 Only written once

 These statements are hidden from other functions

 Boss to worker analogy:

The boss does not know how the worker gets the job done; he just wants it done

Syntax

Preprocesssor lines

function1 prototype; //function prototype

function2 prototype;

int main( )

{

call function1(); //function call

call function2();

……

}

int function1( ) //function definition

……

}

Trang 3

Syntax Explanation

• Function Prototype ( Declaration)

– Tells the compiler that a function of this kind is defined somewhere in the program

• Function Call

– Takes the program control to the called function

• Function Header and Body

– Contains the body of the function i.e all the commands that make up the function

Example

#include <iostream>

using namespace std;

void sum(void); //prototype

int main()

{

sum(); // sum call

return 0;

}

void sum(void)

{

float first, second;

cin >> first >>second; //gets the seconds

cout << first + second; // display the seconds

}

Trang 4

Differentiating Local and Global Variables

Scope

• The life-time of variables exists within the variable’s scope

• After declaration, a variable can be referenced anywhere within its scope

• Every set of braces has its own scope, and can contain local variables

• The moment the set of braces in which a variable was declared ends, the

variable goes out of scope, i.e it can no longer be referenced as an identifier

• A global variable’s scope lies throughout the program

Trang 5

Example

#include <math.h> // to perform math functions

void squareroot(float); // function prototype

float z=0; // global variable

int main(void)

{

float x;

x = 4.0;

z= 6.0;

squareroot(x); //function call

squareroot(z);

}

void squareroot( float a)

{

static float y; // local variable

y = y+sqrt(a) // sqrt() is a built in function to get square root in the cout <<"The answer = " << y <<endl; //math.h library //no error because static variables

// are set to zero by default

}

Trang 6

Inline Functions

• Request to the compiler to insert the function body in the program where it is called

– Saves time in function calls

……

…………

…………

Func1() {…….

…………}

…………

Func2() {

………….

}

Func2 () {…… }

……

…………

…………

Func1()

;

…………

…………

Func2()

;

Func1 () {…… }

main()

main()

Repeated code

placed

Repeated

code

placed in

functions

Trang 7

Important Points about Functions

• It should be noticed that the prototype is written before the main () function This cause the prototype to be visible to all the functions in a file

• The presence of ; should be noted carefully

• The arguments and return type must match to the corresponding variable types

of the prototype and definition

• Note that you can only return one value from a function, however you can pass

several values to a function

• If we want to return more than one value from a function then we have to use pointers

• We can pass constants as well as variable to the functions

Trang 8

QUIZ

Short Questions

1 A function’s single most important role is to

a give a name to a block of code

b reduce program size

c accept arguments and provide a return value

d help organize a program into conceptual units

2 A function itself is called the function d _

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 _

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

9 True or false: When arguments are passed by value, the function works with the original arguments in the program

10 What is the purpose of using argument names in a function declaration?

11 Which of the following can legitimately be passed to a function?

a A constant

b A variable

c A structure

d A header file

12 What is the significance of empty parentheses in a function declaration?

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

15 Where is a function’s return type specified?

16 What functions can access a global variable that appears in the same file with

them?

17 What functions can access a local variable?

18 A static local variable is used to

a make a variable visible to several functions

b make a variable visible to only one function

c conserve memory when a function is not executing

d retain a value when a function is not executing

Trang 9

Exercise

1 Write a function called circarea() that finds the area of a circle in a similar way It should take an argument of type float and return an argument of the same type Write a main() function that gets a radius value from the user, calls circarea(), and displays the result

2 Raising a number n to a power p is the same as multiplying n by itself p times Write a function called power() that takes a double value for n and an int value for

p, and returns the result as a double value Use a default argument of 2 for p, so that if this argument is omitted, the number n will be squared Write a main() function that gets values from the user to test this function

3 Write a function called zeroSmaller() that is passed two int arguments by

reference and then sets the smaller of the two numbers to 0 Write a main() program to exercise this function

Trang 10

Answers

Short Questions

1 d

2 definition

3

void foo()

{

cout << “foo”;

}

4 declaration, prototype

5 body

6 call

7 declarator

8 c

9 false

10 To clarify the purpose of the arguments

11 a, b, c

12 Empty parentheses mean the function takes no arguments

13 one

14 Ttrue

15 at the beginning of the declaration and declaratory

16 those functions defined following the variable definition

17 the function in which it is defined

18 b, d

Trang 11

Exercise Answers

1

// function finds area of circle

#include <iostream>

using namespace std;

float circarea(float radius);

int main()

{

double rad;

cout << “\nEnter radius of circle: “;

cin >> rad;

cout << “Area is “ << circarea(rad) << endl;

return 0;

}

// - float circarea(float r)

{

const float PI = 3.14159F;

return r * r * PI;

}

2

// function raises number to a power

#include <iostream>

using namespace std;

double power( double n, int p=2); //p has default value 2

int main()

{

double number, answer;

int pow;

char yeserno;

cout << “\nEnter number: “; //get number

cin >> number;

cout << “Want to enter a power (y/n)? “;

cin >> yeserno;

if( yeserno == „y‟ ) //user wants a non-2 power?

{

cout << “Enter power: “;

cin >> pow;

answer = power(number, pow); //raise number to pow

}

else

answer = power(number); //square the number

cout << “Answer is “ << answer << endl;

return 0;

}

// - // power()

// returns number n raised to a power p

double power( double n, int p )

{

double result = 1.0; //start with 1

Trang 12

for(int j=0; j<p; j++) //multiply by n

result *= n; //p times

return result;

}

3

// function sets smaller of two numbers to 0

#include <iostream>

using namespace std;

int main()

{

void zeroSmaller(int&, int&);

int a=4, b=7, c=11, d=9;

zeroSmaller(a, b);

zeroSmaller(c, d);

cout << “\na=” << a << “ b=” << b

<< “ c=” << c << “ d=” << d;

return 0;

}

// - // zeroSmaller()

// sets the smaller of two numbers to 0

void zeroSmaller(int& first, int& second)

{

if( first < second )

first = 0;

else

second = 0;

}

Ngày đăng: 17/11/2019, 07:35