0% found this document useful (0 votes)
34 views52 pages

Functions in C++

The document discusses functions in programming fundamentals. It covers standard predefined functions, user-defined functions, value-returning functions, and how to define, call and pass parameters to functions. Examples are provided to illustrate function syntax and usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views52 pages

Functions in C++

The document discusses functions in programming fundamentals. It covers standard predefined functions, user-defined functions, value-returning functions, and how to define, call and pass parameters to functions. Examples are provided to illustrate function syntax and usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

CS118 –

Programming
Fundamentals
Functions
Lecture # 19
Wednesday, December 16, 2020
FALL 2020
FAST – NUCES, Faisalabad Campus

Rizwan Ul Haq
Objectives
2

In this week/classes, you will:


 Learn about standard (predefined) functions and
discover how to use them in a program
 Learn about user-defined functions
 Examine value-returning functions, including actual
and formal parameters
 Explore how to construct and use a value-returning,
user-defined function in a program

CS118 - FALL 2020


Modular Programming
3

 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

CS118 - FALL 2020


Introduction
4

 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

CS118 - FALL 2020


Introduction
5

 Functions are like building blocks


 They allow complicated programs to be divided into
manageable pieces
 Some advantages of functions:
 A programmer can focus on just that part of the program
and construct it, debug it, and perfect it
 Different people can work on different functions
simultaneously
 Can be re-used (even in different programs)
 Enhance program readability

CS118 - FALL 2020


Introduction (cont'd.)
6

 Functions
 Called modules
 Like miniature programs
 Can be put together to form a larger program

CS118 - FALL 2020


Predefined Functions
7

 In algebra, a function is defined as a rule or


correspondence between values, called the
function’s arguments, and the unique value of the
function associated with the arguments
 If f(x) = 2x + 5, then f(1) = 7, f(2) = 9, and f(3) = 11
 1, 2, and 3 are arguments
 7, 9, and 11 are the corresponding values

CS118 - FALL 2020


Predefined Functions (cont'd.)
8

 Some of the predefined mathematical functions


are:
 sqrt(x);
 sqrt( 4 );
 sqrt( 3 - 6x );
 pow(x, y);
 floor(x);
 Predefined functions are organized into separate
libraries
 I/O functions are in iostream header
 Math functions are in cmath/math header

CS118 - FALL 2020


Predefined Functions (cont'd.)
9

 pow(x,y) calculates xy
 pow(2, 3) = 8.0
 Returns a value of type double
 x and y are the parameters (or arguments)
 This function has two parameters
 sqrt(x) calculates the nonnegative square root of x,
for x >= 0.0
 sqrt(2.25) is 1.5
 Type double

CS118 - FALL 2020


Predefined Functions (cont'd.)
10

 The floor function floor(x) calculates largest whole


number not greater than x
 floor(48.79) is 48.0
 Type double
 Has only one parameter

CS118 - FALL 2020


Predefined Functions (cont'd.)
11

CS118 - FALL 2020


Predefined Functions (cont'd.)
12

CS118 - FALL 2020


Predefined Functions (cont'd.)
13 Example 6-1
//How to use predefined function
#include <iostream>
#include <cmath>
#include <cctype>
#include <cstdlib>
using namespace std;
int main(){
int x;
double u, v;
cout << "Line 1: Uppercase a is "
<< static_cast<char> (toupper('a’)) << endl; //Line 1
u = 4.2 ; //Line 2
v = 3.0 ; //Line 3
cout << "Line 4: " << u << " to the power of "
<< v << " = " << pow(u,v) << endl; //Line 4
cout << "Line 5 : 5.0 to the power of 4 = "
<< pow(5.0,4) << endl; //Line 5

u = u + pow(3.0, 3); //Line 6


cout << "Line 7: u = " << u << endl; //Line 7

x = -15 ; //Line 8
cout << "Line 9: Absolute value of " << x
<< " = " << abs(x) << endl; //Line 9
return 0;
}
CS118 - FALL 2020
User-Defined Functions
14

 Value-returning functions: have a return type


 Return a value of a specific data type using the return
statement function, called the type of the function
 You need to add the following items :
 The name of the function
 The number of parameters, if any
 The data type of each parameter
 The data type of the value computed (that is, the value
returned) by the Function
 Void functions: do not have a return type
 Do not use a return statement to return a value

CS118 - FALL 2020


Syntax: Value-Returning function
15

functionType functionName(formal parameter list)


{
statements
}

CS118 - FALL 2020


Function Header
16

 The function header consists of


 the function return type
 the function name
 the function parameter list
 Example:
int main()

CS118 - FALL 2020


Function Return Type
17

 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
void printHeading()
{
cout << "\tMonthly Sales\n";
}

CS118 - FALL 2020


Syntax: Formal Parameter List
18

Function Return Type Function name


Function parameter
Formal Heading
int abs(int number) {

if (number<0) Formal parameter list


number = -number;
return number;
}
Formal Body

CS118 - FALL 2020


Defining and Calling Functions
19

 Function call: Statement that causes a function to


execute
 Function definition: Statements that make up a function

int abs(int number);


Similarly the function abs might have the following definition:

int abs(int number)


{
if(number < 0)
number = -number;

return number;
}

CS118 - FALL 2020


Function Definition
20

 Definition includes
 return type: Data type of the value the function returns to
the part of the program that called it
 name: Name of the function. Function names follow same
rules as variable names
 parameter list: Variables that hold the values passed to the
function
 body: Statements that perform the function’s task

CS118 - FALL 2020


Calling a Function
21

 To call a function, use the function name followed


by () and ;
printHeading();
 When a function is called, the program executes
the body of the function
 After the function terminates, execution resumes in
the calling function at the point of call

 main() is automatically called when the program


starts
 main() can call any number of functions
 Functions can call other functions

CS118 - FALL 2020


Function Call
22

CS118 - FALL 2020


Syntax: Actual Parameter List
23

Can be zero
parameter

CS118 - FALL 2020


Actual Parameter Vs Formal
24 Parameter
Suppose that the heading of the function pow is:

double pow(double base, double exponent);

From the heading of the function pow, it follows that the formal
parameters of pow are base and exponent. Consider the following
statements:

double u = 2.5;
double v = 3.0;
double x, y;
x = pow(u, v); //Line1
y = pow(2.0, 3.2) + 5.1; //Line2
cout << u << " to the power of 7 = " << pow(u, 7) << endl; //Line3

Formal Parameter: A variable declared in the function heading.


Actual Parameter: A variable or expression listed in a call to function.

CS118 - FALL 2020


25

CS118 - FALL 2020


Function Call Notes
26

 Value of argument is copied into parameter when


the function is called
 Function can have >= 0 parameter(s)
 There must be a data type listed in the prototype ()
and an argument declaration in the function
heading () for each parameter
 Arguments will be promoted/demoted as necessary
to match parameters

CS118 - FALL 2020


Calling Functions with Multiple
27 Arguments
 When calling a function with multiple arguments:
 The number of arguments in the call must match the
function prototype and definition
 The first argument will be copied into the first parameter, the
second argument into the second parameter, etc.

CS118 - FALL 2020


Calling Functions with Multiple
28 Arguments – an Illustration
void displayData(int h, int w) //heading
{
cout << "Height = " << h << endl;
cout << "Weight = " << w << endl;
}

displayData(height, weight); //Call

CS118 - FALL 2020


Value-Returning Functions --
29 Example
int abs(int number)
{
if(number < 0)
number = -number;

return number;
}

CS118 - FALL 2020


return Statement
30

 Once a value-returning function computes the


value, the function returns this value via the return
statement
 It passes this value outside the function via the return
statement

CS118 - FALL 2020


Syntax: return Statement
31

 The return statement has the following syntax:

 In C++, return is a reserved word


 When a return statement executes
 Function immediately terminates
 Control goes back to the caller
 When a return statement executes in the function
main, the program terminates
e.g return 0;

CS118 - FALL 2020


Returning a Value From a Function
32

 return statement can be used to return a value from


the function to the module that made the function
call
 Prototype and definition must indicate data type of
return value (not void)
 Calling function should use return value
 assign it to a variable
 send it to cout
 use it in an arithmetic computation
 use it in a relational expression
 Pass it as a parameter to another function

CS118 - FALL 2020


Syntax: return Statement (cont’d.)
33

CS118 - FALL 2020


Example
34

CS118 - FALL 2020


Function to compare three numbers
35

CS118 - FALL 2020


Returning a Boolean Value
36

 Function can return true or false


 Declare return type in function prototype and
heading as bool
 Function body must contain return statement(s) that
return true or false
 Calling function can use return value in a relational
expression

CS118 - FALL 2020


Boolean return Example
37
bool isValid(int); // prototype

bool isValid(int val) // heading


{
int min = 0, max = 100;
if (val >= min && val <= max)
return true;
else
return false;
}

if (isValid(score)) // call

CS118 - FALL 2020
Function Prototypes
38

 The compiler must know the following about a


function before it is called
 name
 return type
 number of parameters
 data type of each parameter

CS118 - FALL 2020


Function Prototype
39

Function prototype: Function heading


without the body of the function
Syntax:

It is not necessary to specify the variable


name in the parameter list
The data type of each parameter must be
specified

CS118 - FALL 2020


Function Prototype
40

 The function heading without the body of the


function.

CS118 - FALL 2020


Prototype Notes
41

 Place prototypes near top of program


 Program must include either prototype or full
function definition before any call to the function,
otherwise a compiler error occurs
 When using prototypes, function definitions can be
placed in any order in the source file. Traditionally,
main is placed first.
 Use a function prototype (similar to the heading of
the function
 Header: void printHeading()
 Prototype: void printHeading();

CS118 - FALL 2020


Function Prototype (Illustration)
42

CS118 - FALL 2020


Function Prototype (Illustration
43 cont'd.)

CS118 - FALL 2020


Example Program I
44 1
2
// C++ Program
// Creating and using a programmer-defined function.
3 #include <iostream>
4 Function prototype: specifies
5 using std::cout; data types of arguments and
6 using std::endl; return values. square expects
7
and int, and returns an int.
8 int square(int); // function prototype
9
10 int main()
11 {
12 // loop 10 times and calculate and output
13 // square of x each time
14 for (int x = 1; x <= 10; x++) Parentheses () cause function
15 cout << square(x) << " "; // function call
16
to be called. When done, it
17 cout << endl; returns the result.
18
19 return 0; // indicates successful termination
20
21 } // end main
22
23 // square function definition returns square of an integer
24 int square(int y) // y is a copy of argument to function
25 {
26 return y * y; // returns square of y as an int
27 Definition of square. y is a copy
28 } // end function square of the argument passed.
CS118 - FALL 2020 Returns y * y, or y squared.
Output
45

1 4 9 16 25 36 49 64 81 100

CS118 - FALL 2020


Example Program II
46 1
2
// C ++ Program
// Finding the maximum of three floating-point numbers.
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 double maximum(double, double, double); // function prototype
10
11 int main()
12 {
13 double number1;
14 double number2; Function maximum takes 3
15 double number3;
16
arguments (all double) and
17 cout << "Enter three floating-point numbers: "; returns a double.
18 cin >> number1 >> number2 >> number3;
19
20 // number1, number2 and number3 are arguments to
21 // the maximum function call
22 cout << "Maximum is: "
23 << maximum(number1, number2, number3) << endl;
24
25 return 0; // indicates successful termination
26
27 } // end main
28

CS118 - FALL 2020


Example Program II
47
Comma separated list
29 // function maximum definition; for multiple parameters.
30 // x, y and z are parameters
31 double maximum(double x, double y, double z)
32 {
33 double max = x; // assume x is largest
34
35 if (y > max) // if y is larger,
36 max = y; // assign y to max
37
38 if (z > max) // if z is larger,
39 max = z; // assign z to max
40
41 return max; // max is largest value
42
43 } // end function maximum

CS118 - FALL 2020


Sample run
48

Enter three floating-point numbers: 99.32 37.3 27.1928


Maximum is: 99.32

Enter three floating-point numbers: 1.1 3.333 2.22


Maximum is: 3.333

Enter three floating-point numbers: 27.9 14.31 88.99


Maximum is: 88.99

CS118 - FALL 2020


Value-Returning Functions: Some
49 Peculiarity

CS118 - FALL 2020


Value-Returning Functions: Some
50 Peculiarity (cont'd.)

CS118 - FALL 2020


Value-Returning Functions: Some
51 Peculiarity (cont'd.)

CS118 - FALL 2020


Questions
52

CS118 - FALL 2020

You might also like