Sie sind auf Seite 1von 44

ENGG1002 Computer Programming and Applications

Prepared by Dr. K.K.Y. Wong


Top-Down Design
 A good way to design a program is to break down the task to
be accomplished into a few sub-tasks
 Each sub-task can be further decomposed into smaller sub-
tasks, and this process is repeated until all sub-tasks are small
enough that their implementations become manageable
 This approach is called top-down design (a.k.a. divide and
conquer)
Generate the standard deviation

Read in data Compute standard deviation Output the result to screen

Compute mean Compute variance Compute square root


2
Functions
 Preserving the top-down design structure in a program will
make it easier to understand and change the program, as well
as to write, test, and debug the program
 In C++, sub-tasks are implemented as functions
 A function is a group of statements that is executed when it is called
from some point of the program
 E.g., the main function main() in previous examples
 A program is composed of a collection of functions
 When a program is put into execution, it always starts at the
main function, which may in turn call other functions

3
Function Definition
 A function is defined using a function definition which
 Describes how a function computes the value it returns
 Consists of a function header followed by a function body
 The function header specifies the type of the return value, the function
name (identifier), and the list of parameters (with types and identifiers)
 The function body consists of variable declarations and executable
statements enclosed within a pair of braces { }
Syntax
function header type_ret func_name(type_1 par_1, type_2 par_2, …)
{
// variable declarations

function body // executable statements

}
4
Function Definition
 Example:
return type: function name: parameters:
double f2c double f

function header double f2c(double f)


{
// Fahrenheit to Celsius Conversion variable declaration
double c;
function body c = (f – 32)*5/9; executable statement
return c;
}

return statement
 returns the specified value to the caller

 terminates the execution of the function

5
Function Call
 A function call (i.e., the process of calling a function) is made
using the function name with the necessary parameters
 A function call is itself an expression, and can be put in any places
where an expression is expected
 Example:
double Tc = f2c(98.6);

 Parameters vs arguments
 The parameters used in the function definition are called formal
parameters or simply parameters. They are placeholders in the function
 The actual values passed to a function in a function call are referred to
as actual parameters or arguments. They are the actual values used in
the execution of the function to produce the return value

6
Function Call
 The arguments used in a function call can be constants,
variables, expressions, or even functions, e.g.,
double Tc1 = f2c(98.6); // a constant
double Tc2 = f2c(Tf); // a variable
double Tc3 = f2c(Tf – 10.0); // an expression
double Tc4 = f2c(c2f(37.0)); // a function

 In using expressions as arguments, the expressions will be


evaluated to produce a value before the function call is made
 Since a function is also an expression, the mechanism of using
functions as arguments is identical to that of using expressions

7
Function Declaration
 A function must be defined before the function call is made
 One way to do this is to place the function definition before the
function call in the source file, e.g., before main()
 Alternatively, the function definition can be placed anywhere in the
source file by including a function declaration before the function call
 A function declaration is similar to a function header except
that it must be followed by a semicolon ; and the identifiers in
the parameter list can be changed or even omitted. It provides
all the information needed in making a function call
Syntax
type_ret func_name(type_1 par_1, type_2 par_2, …);
or
type_ret func_name(type_1, type_2, …);
8
Function Declaration
 Examples:
#include <iostream> #include <iostream>
using namespace std; #include <iostream>
using namespace std; #include <iostream>
using namespace std; using namespace std;
double f2c(double f) double f2c(double f);
{ double f2c(double fah); double f2c(double);
// Fahrenheit to Celsius int main()
double c; int main()
{ int main()
c = (f – 32)*5/9; {
…. {
return c; ….
Tc = f2c(Tf); ….
} Tc = f2c(Tf);
…. Tc = f2c(Tf);
….
} ….
int main() } }
{ double f2c(double f)
…. double f2c(double f)
{ double f2c(double f)
Tc = f2c(Tf); {
// Fahrenheit to Celsius {
…. // Fahrenheit to Celsius
double c; // Fahrenheit to Celsius
} double c;
c = (f – 32)*5/9; double c;
c = (f – 32)*5/9;
return c; c = (f – 32)*5/9;
return c;
} return c;
} }

9
Flow of Control
 When a program is put into execution
 It always starts at the main function no matter where its definition is in
the source file
 The statements in the main function are executed sequentially from top
to bottom, and the control is passed from one statement to another
 When a function call is encountered, the execution of the current
function is suspended and the control is passed to the called function
 Likewise, the statements in the called function are executed from top to
bottom, and the control is passed from one statement to another
 When a return statement is encountered, the control is passed back to the
calling function together with the return value
 The main function will resume at the calling statement
 When a return statement in the main function is encountered, the
program ends

10
Flow of Control
 The program on the right #include <iostream>
using namespace std;
converts a user input
body temperature from double f2c(double f)
{
degrees Fahrenheit to // Fahrenheit to Celsius Conversion
degrees Celsius, and double c;
c = (f – 32)*5/9;
determines if the user return c;
have a fever }

 It consists of two int main()


{
functions: double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
 main() – controls
cin >> Tf;
general logic flow and
Tc = f2c(Tf);
handles I/O cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;
 f2c() – performs
if (Tc > 37.0)
Fahrenheit to Celsius cout << “You have a fever!” << endl;
conversion
return 0;
}
11
Flow of Control
#include <iostream>
using namespace std;

double f2c(double f)
{
// Fahrenheit to Celsius Conversion
function definition double c;
c = (f – 32)*5/9;
return c;
 The function definition is }

placed before where the int main()


function call is made so {
that the compiler knows double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
how to handle the cin >> Tf;
function call function call
Tc = f2c(Tf);
 Alternatively, a function cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;
declaration can be used
if (Tc > 37.0)
and the definition can cout << “You have a fever!” << endl;
then be placed after the
main function return 0;
}
12
Flow of Control
 When the program is put #include <iostream>
using namespace std;
into execution, it always
starts at the main double f2c(double f)
{
function // Fahrenheit to Celsius Conversion
double c;
c = (f – 32)*5/9;
return c;
}

int main()
{
double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

Tc = f2c(Tf);
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
}
13
Flow of Control
 The statements in the #include <iostream>
using namespace std;
main function are
executed sequentially double f2c(double f)
{
from top to bottom // Fahrenheit to Celsius Conversion
double c;
 The control is passed c = (f – 32)*5/9;
from one statement to return c;
}
another
int main()
{
double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

Tc = f2c(Tf);
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
}
14
Flow of Control
 The statements in the #include <iostream>
using namespace std;
main function are
executed sequentially double f2c(double f)
{
from top to bottom // Fahrenheit to Celsius Conversion
double c;
 The control is passed c = (f – 32)*5/9;
from one statement to return c;
}
another
int main()
{
double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

Tc = f2c(Tf);
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
}
15
Flow of Control
 The statements in the #include <iostream>
using namespace std;
main function are
executed sequentially double f2c(double f)
{
from top to bottom // Fahrenheit to Celsius Conversion
double c;
 The control is passed c = (f – 32)*5/9;
from one statement to return c;
}
another
int main()
{
double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

Tc = f2c(Tf);
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
}
16
Flow of Control
 When a function call is #include <iostream>
using namespace std;
encountered, the
execution of the current double f2c(double f)
{
function is suspended // Fahrenheit to Celsius Conversion
double c;
c = (f – 32)*5/9;
return c;
}

int main()
{
double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

Tc = f2c(Tf);
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
}
17
Flow of Control
 The values of the #include <iostream>
using namespace std;
arguments are copied to
the formal parameters of double f2c(double f)
{
the called function // Fahrenheit to Celsius Conversion
double c;
 The control is passed to c = (f – 32)*5/9;
the called function return c;
}

int main()
{
double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

Tc = f2c(Tf);
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
}
18
Flow of Control
 Likewise, the statements #include <iostream>
using namespace std;
in the called function are
executed from top to double f2c(double f)
{
bottom // Fahrenheit to Celsius Conversion
double c;
 The control is passed c = (f – 32)*5/9;
from one statement to return c;
}
another
int main()
{
double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

Tc = f2c(Tf);
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
}
19
Flow of Control
 Likewise, the statements #include <iostream>
using namespace std;
in the called function are
executed from top to double f2c(double f)
{
bottom // Fahrenheit to Celsius Conversion
double c;
 The control is passed c = (f – 32)*5/9;
from one statement to return c;
}
another
int main()
{
double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

Tc = f2c(Tf);
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
}
20
Flow of Control
 When a return statement #include <iostream>
using namespace std;
is encountered, the
control is passed back to double f2c(double f)
{
the calling function // Fahrenheit to Celsius Conversion
together with the return double c;
c = (f – 32)*5/9;
value return c;
}

int main()
{
double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

Tc = f2c(Tf);
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
}
21
Flow of Control
 The main function will #include <iostream>
using namespace std;
resume at the calling
statement double f2c(double f)
{
// Fahrenheit to Celsius Conversion
double c;
c = (f – 32)*5/9;
return c;
}

int main()
{
double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

Tc = f2c(Tf);
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
}
22
Flow of Control
 The statements in the #include <iostream>
using namespace std;
main function are
executed sequentially double f2c(double f)
{
from top to bottom // Fahrenheit to Celsius Conversion
double c;
 The control is passed c = (f – 32)*5/9;
from one statement to return c;
}
another
int main()
{
double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

Tc = f2c(Tf);
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
}
23
Flow of Control
 The statements in the #include <iostream>
using namespace std;
main function are
executed sequentially double f2c(double f)
{
from top to bottom // Fahrenheit to Celsius Conversion
double c;
 The control is passed c = (f – 32)*5/9;
from one statement to return c;
}
another
int main()
{
double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

Tc = f2c(Tf);
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
}
24
Flow of Control
 The statements in the #include <iostream>
using namespace std;
main function are
executed sequentially double f2c(double f)
{
from top to bottom // Fahrenheit to Celsius Conversion
double c;
 The control is passed c = (f – 32)*5/9;
from one statement to return c;
}
another
int main()
{
double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

Tc = f2c(Tf);
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
}
25
Flow of Control
 When a return statement #include <iostream>
using namespace std;
in the main function is
encountered, the double f2c(double f)
{
program ends // Fahrenheit to Celsius Conversion
double c;
c = (f – 32)*5/9;
return c;
}

int main()
{
double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

Tc = f2c(Tf);
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
}
26
Void Functions
 In some situations, a function simply carries out some
operations and produces no return value
 In this case, the void type specifier, which indicates absence of
type, can be used
 A function with no return value is called a void function
 The return statement in a void function does not specify any
return value. It is used to return the control to the calling
function
 If a return statement is missing in a void function, the control
will be returned to the calling function after the execution of
the last statement in the function

27
Void Functions
 Examples:
void print_msg()
{
cout << “This is a void function.” << endl;
return;
No return value
}

void print_msg()
{
cout << “This is a void function.” << endl;
}
No return statement

28
Local Variables
 Variable declared within a function, including formal para-
meters, are private or local to that particular function, i.e., no
other function can have direct access to them
 Local variables in a function come into existence only when
the function is called, and disappear when the function is
exited
 Do not retain their values from one function call to another
 Their values must be explicitly set upon each entry
 Local variables declared within the same function must have
unique identifiers, whereas local variables of different
functions may use the same identifier

29
Local Variables
Local variables of f2c():
 Examples: #include <iostream> f, Tc
using namespace std;

double f2c(double f) Local variables of main():


{ Tf, Tc
// Fahrenheit to Celsius Conversion
double Tc;
Tc = (f – 32)*5/9; The local variables Tc of
return Tc;
}
f2c() and Tc of main()
are unrelated
int main()
{
double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

Tc = f2c(Tf);
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
} 30
Local Variables
 Examples: #include <iostream>
using namespace std;

double f2c(double f)
{
// Fahrenheit to Celsius Conversion The compiler will give an error
Tc = (f – 32)*5/9; message as Tc is a local variable
return Tc;
of main() but not f2c()
}

int main()
{
double Tf, Tc;
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

Tc = f2c(Tf);
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
}
31
Global Variables
 Variables may also be declared outside all functions
 Such variables are called global variables because they can be
accessed by all functions, i.e., globally accessible
 Global variables remain in existence permanently
 Retain their values even after the functions that set them have
returned
 Can be used instead of arguments to communicate data between
functions
 The values of global variables can be changed by several functions
 Hard to trace, especially when something goes wrong
 Not recommended and should be avoided!

32
Global Variables
 Examples: #include <iostream>
using namespace std;
Global variables:
double Tf, Tc;
Tf, Tc
void f2c()
{
// Fahrenheit to Celsius Conversion
Tc = (Tf – 32)*5/9;
}

int main()
{
cout << “Please enter your body temperature in degrees Fahrenheit: ”;
cin >> Tf;

f2c();
cout << “Your body temperature is ” << Tc << “ degrees Celsius.” << endl;

if (Tc > 37.0)


cout << “You have a fever!” << endl;

return 0;
}
33
Scopes of Variables
 The scope of a variable is the portion of a program that the
variable is well-defined and can be used
 A variable cannot be referred to beyond its scope
 The scope of a local / global variable starts from its declaration
up to the end of the block / file
 A block is delimited by a pair of braces { }
 Variables declared in outer blocks can be referred to in an inner block
 Variable can be declared with the same identifier as long as
they have different scopes
 Variables in an inner block will hide any identically named variables in
outer blocks

34
Scopes of Variables
Scope of the formal
 Examples: int func(int x, int y) parameters x and y
{

if (x > y) Scope of the local
{ variable k
int k;
….
} Scope of the local
int z; variable z

}
Scope of the global
double a; variable a
int main()
{
int x, y, z; Scope of the local

if (…)
variables x, y and z
{
int x;
… Scope of the local
} variable x in the
… inner block
}
35
Scopes of Variables
 Example:
Screen output
#include <iostream> Outer block: i = 0
using namespace std;
Inner block: i = 100
int main() Outer block: i = 0
{
int i = 0;

cout << “Outer block: i = ” << i << endl;

{
int i = 100;
cout << “Inner block: i = ” << i << endl;
}

cout << “Outer block: i = ” << i << endl;

return 0;
}

36
Call by Value
 When a function call takes place, the values of the arguments
are copied to the formal parameters of the function
 This mechanism of parameter-passing is known as call by value
 Recall that formal parameters are local variables
 Any changes made to their values are local to the function and will not
alter the arguments in the calling function
 Disappear when the function exits, only the return value will be passed
back to the calling function

37
Call by Value
 Example:
Screen output
#include <iostream> x = 0, y = 100
using namespace std;
a = 0, b = 100
void swap(int a, int b); a = 100, b = 0
x = 0, y = 100
int main()
{
int x = 0, y = 100;
cout << “x = ” << x << “, y = “ << y << endl;
swap(x, y);
cout << “x = ” << x << “, y = “ << y << endl;
return 0;
}

void swap(int a, int b)


{
cout << “a = ” << a << “, b = “ << b << endl;
int temp = a;
a = b;
b = temp;
cout << “a = ” << a << “, b = “ << b << endl;
}
38
Call by Reference
 In order to allow a function to modify the arguments
(variables) in the calling function, another parameter-passing
mechanism known as call by reference should be used
 In call by reference
 Memory cells are not allocated to the formal parameters by the
compiler
 The formal parameters will refer to the same memory cells of the
arguments in run-time, and therefore the arguments must be variables
 Any changes made to the values of the formal parameters will be
reflected in the arguments as they share the same memory cells

39
Call by Reference
 To indicate a formal parameter will be passed by reference, an
ampersand sign & is placed in front of its identifier in the
function header and function declaration

Syntax (function header)


type_ret func_name(type_1 &par_1, type_2 &par_2, …)

Syntax (function declaration)


type_ret func_name(type_1 &par_1, type_2 &par_2, …);

40
Call by Reference
 Example:
Screen output
#include <iostream> x = 0, y = 100
using namespace std;
a = 0, b = 100
void swap(int &a, int &b); a = 100, b = 0
x = 100, y = 0
int main()
{
int x = 0, y = 100;
cout << “x = ” << x << “, y = “ << y << endl;
swap(x, y);
cout << “x = ” << x << “, y = “ << y << endl;
return 0;
}

void swap(int &a, int &b)


{
cout << “a = ” << a << “, b = “ << b << endl;
int temp = a;
a=b
b = temp;
cout << “a = ” << a << “, b = “ << b << endl;
}
41
Pre-defined Functions
 C++ comes with libraries of pre-defined functions that
programmers can use in their programs
 The function definitions are stored in separate files and have been pre-
compiled into object codes
 The function declarations are stored in files known as the header files
 Like user-defined functions, these pre-defined functions must
be declared before a function call is made
 To declare a pre-defined function, simply include the corresponding
header file using the include directive #include <…>
 E.g., #include <iostream> tells the compiler to include the header file
iostream which contains the declarations of functions for handling
standard input and output streams

42
Pre-defined Functions
 Some pre-defined functions
Function Description Library Header
double sqrt(double x) Square root of x cmath
double pow(double x, double y) x to the power of y (i.e., xy) cmath
double fabs(double x) Absolute value of x cmath
double ceil(double x) Round up the value of x cmath
double floor(double x) Round down the value of x cmath
int abs(int x) Absolute value of x cstdlib
int rand() A random integer cstdlib

43
Pre-defined Functions
 Example:
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
// Compute the root mean square of 10 input numbers
int i;
double n, sq_sum = 0;

for(i=0; i<10; i++)


{
cout << i+1 << “: ”;
cin >> n;
sq_sum += pow(n, 2.0);
}

cout << “The root mean square is ” << sqrt(sq_sum/10) << endl;

return 0;
}

44

Das könnte Ihnen auch gefallen