Tải bản đầy đủ (.ppt) (19 trang)

C++ lecture 9

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (259.28 KB, 19 trang )

C++ Programming
Lecture 9

Functions – Part I
The Hashemite University
Computer Engineering
Department
(Adapted from the textbook slides)


Outline


Introduction.



C++ program components.



Math library functions.



Functions:







Prototype.
Definition.
Function call.

Header files.

The Hashemite University

2


Introduction






Till now we have learned the basic concepts
of C++.
All the programs that we have written are
simple, have few lines of code, and flat
(i.e. all the code resides inside the
main() body).
But:






What about large programs?
What about code reuse (when the same code block is used
many times within the program)?

Divide and conquer technique:
 Construct a program from smaller pieces or
components
 Each piece more manageable than the original
program
The Hashemite University

3


Program Components in C++
I



C++ modules are functions and classes.
Programs are written by:






Combining new functions with “prepackaged”
functions in the C++ standard library.


The standard library provides a rich
collection of functions.
Functions are invoked by a function call




A function call specifies the function name and
provides information (as arguments) that the
called function needs.
Similar to the 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.
The Hashemite University

4


Program Components in C++
II


Function definition:









It is the body of the function which include all the
processing done by the function.
It makes use of the parameters (arguments) passed by
the function call and specifies what will be returned by
the function (result of the function).

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

The Hashemite University

5


Math Library Functions I


Math library functions







Allow the programmer to perform common
mathematical calculations
Are used by including the header file <cmath>
or <math.h>

Functions called by writing
functionName (argument)



Example
cout << sqrt( 900.0 );





Calls the sqrt (square root) function. The
preceding statement would print 30
The sqrt function takes an argument of type
double and returns a result of type double, as
do all functions in the math library
The Hashemite University

6


Math Library Functions II





All math library functions return
double values (as a result).
Function arguments can be


Constants
sqrt( 4 );



Variables
sqrt( x );



Expressions
sqrt( sqrt( x ) ) ;
sqrt( 3 - 6x );
The Hashemite University

7


Math Library Functions III




















acos(x) inverse cosine, -1 <= x <= +1, returns value in
radians in range 0 to PI
asin(x) inverse sine, -1 <= x <= +1, returns value in
radians in range 0 to PI
atan(x) inverse tangent, returns value in radians in range
-PI/2 to PI/2
cos(x) returns cosine of x, x in radians
sin(x) returns sine of x, x in radians
tan(x) returns tangent of x, x in radians
exp(x) exponential function, e to power x
log(x) natural log of x (base e), x > 0
sqrt(x) square root of x, x >= 0
fabs(x) absolute value of x
floor(x) largest integer not greater than x

ceil(x) smallest integer not less than x.
pow(x, y) returns xy.
fmod(x, y) computes the modulus of floating point numbers.
Note: Have a look at Figure 3.2 in chapter 3.
The Hashemite University

8


Functions


Functions




Local variables






Allow the programmer to modularize a program.
Known only in the function in which they are
defined.
All variables declared in function definitions are
local variables.


Parameters


Local variables passed when the function is called
that provide the function with outside information.
The Hashemite University

9


1

// Fig. 3.3: fig03_03.cpp

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

18
19
20
21
22
23

// Creating and using a programmer-defined function
#include <iostream>

1

4

using std::cout;
using std::endl;

Notice how parameters and return
value are declared.

int square( int );

// function prototype

int main()
{
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " ";
cout << endl;
return 0;

}
// Function definition
int square( int y )
{
return y * y;
}

9

16

25

36

49

64

81

100

The Hashemite University

10


Function Definition





Create customized functions to:
 Take in data
 Perform operations
 Return the result
Format for function definition:
return-value-type function-name( parameter-list )
{
declarations and statements
}




Function name is any valid identifier.
Example:
int square( int y)
{
return y * y;
}
The Hashemite University

11


Function Prototypes I





Used by the compiler to check the validity
of the function call within the main program
(function name, its return data type, number
of arguments, their data types, and their
order).
Function prototype consist of:
 Function name
 Parameters




Information the function takes in, can be void.

Return type




Type of information the function passes back to caller
(default int)
void signifies the function returns nothing
The Hashemite University

12


Function Prototypes II











If you have passed arguments of different data types
from the one specified in the function prototype and
definition, the compiler will convert them to the
proper data type for the function (implicit
casting).
However, sometimes implicit casting is not possible.
In this case the compiler will give a syntax error.
Not following the Promotion Rule in C++ can cause
errors in the obtained results. E.g. converting from
double to integer causes data loss but converting
integer to double is not.
Function prototype is Only needed if function
definition comes after the function call in the
program (after the main()).
Another example:
int maximum( int, int, int );



Takes in 3 ints

Returns an int

The Hashemite University

13


#include <iostream>
#include<cstdlib>
using namespace std;
int random (int , float, int);
int main ()
{
cout<return 0;
}
int random (int x,float y, int z)

Will print
15
Will print 3 5
99

Which one will be printed first
?

{
cout<"<return 8+rand()%17;

}
The Hashemite University

14


Functions Returning
Results


Three ways to return to the point at
which we have called a function:








Reaching closing brace } of the function definition
(the function returns nothing).
Executing
return; (the function returns nothing).
Executing
return result; (the function returns a specific
result).
Note: You cant put a function that doesn't return a
value in a cout statement
The Hashemite University


15


#include <iostream>
using namespace std;
void printer1 ();// function
prototype
int main ()
{
printer1(); //function
call
return 0;
}
void printer1 ();
{
cout<<"C is : "<<‘c’<}
Function doesn't return a
value

#include <iostream>
#include<cstdlib>
using namespace std;
int random (int, int, int);
int main ()
{
cout<return 0;
}

int random (int x,int y, int z)
{
cout<"<return 8+rand()%17;
}

Function returns
value

The Hashemite University

16


1

// Fig. 3.4: fig03_04.cpp

2

// Finding the maximum of three integers

3

#include <iostream>

4
5


using std::cout;

6

using std::cin;

7

using std::endl;

8
9

int maximum( int, int, int );

// function prototype

10
11 int main()
12 {
13

int a, b, c;

14
15

cout << "Enter three integers: ";

16


cin >> a >> b >> c;

17
18

// a, b and c below are arguments to

19

// the maximum function call

20

cout << "Maximum is: " << maximum( a, b, c ) << endl;

The Hashemite University

17


21
22
23
24
25
26
27
28
29

30
31
32
33
34
35
36
37
38
39

return 0;
}
// Function maximum definition
// x, y and z below are parameters to
// the maximum function definition
int maximum( int x, int y, int z )
{
int max = x;
if ( y > max )
max = y;
if ( z > max )
max = z;
return max;
}

Enter three integers: 22 85 17
Maximum is: 85
Enter three integers: 92 35 14
Maximum is: 92

Enter three integers: 45 19 98
Maximum is: 98

The Hashemite University

18


Additional Notes


This lecture covers the following material from the
textbook:


Chapter 3: Sections 3.1 – 3.7

The Hashemite University

19



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×