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

4 Functions

Uploaded by

ii9593375
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views52 pages

4 Functions

Uploaded by

ii9593375
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

CS242

COMPUTER
PROGRAMMING

C++ Functions
Modules
2

 Blocks of codes with an independent functionality.


 Written and tested separately.
 Combined to form a complete program.
 Modules either control or general:
 Control
 Called “Main”
 each program include only one control module.
 General
 Perform manipulations on data e.g. calculation, print, read and
validation.
C++ Modules
3

 All Modules in C++ are called “functions”


 called methods or procedures in other languages.

 Functions can be
 Programmer-defined.
 Built-in: pow, sqrt, .. etc.

 Advantage
 make programs easier to write, test, debug and maintain.
4
5
Functions Syntax
6

1 2 3
ReturnType FctName(Parameter List) Function Header
{
action1;
action2; 1

..
Function Body
actionN; 2
return value ;
}
Function Name and Return
7
Type
 Function name follows rules of naming identifiers as variables and
constants.
 Function return ONLY one value.
 Function return types:
 Built-in data types.
 User-defined data types.
 Nothing is returned by using keyword void.

int f1(Parameter List) void f2(Parameter List) void f2(Parameter List)


{ { {

return value ; return;

} } }
Function Parameters
8

 Provide the communication links between the main program and its
functions.

 Parameters declared in the function header within parenthesis.

 Either have a single, multiple parameters or have no parameters.

 List of a parameters are separated by commas.

 Each parameter must be defined as follows: char f1(int x, int y)


{

return value ;
DataType parameterName
}
Problem
9

Write a program that asks the user for the exam grade and prints a
message indicating if the user has passed the exam or not.
#include <iostream>
using namespace std;

int main()
{
int grade;

cout<<"Enter your grade:\n";


cin>>grade;

if (grade>60) cout<<"You passed";


else cout<<“You failed";

return 0;
}

Can you solve the problem using functions ?


Selecting Functions -1
10

 Divide the program into tasks:


 Read student grade.
 Print appropriate message.

 Naming functions:
 Read_Grade
 Display_Msg main Fct
 main

Read_Grade Display_Msg
Display_Msg
Analyzing Flow of Control-2

een
s cr n
on Mai
age l t o
ess ontro
1

ym c
p l a t urn
Dis D re
Start here

AN
end
4
D s de
AN a
g e d_ G r
ssa a
me by Re
l ay
i s p rn e d
t o d re t u
ok e de
I n v e gra
main Fct

th
er
us
e
th
m
f ro
d
ea r
er ut
us inp
m e
return 0 ;

f ro th
ut n
ur
i np t

3
ad Re
re
to

Read_Grade
ke
vo
In

2
6
11
Read_Grade
Main Fct

Return the input read from the user


Invoke to read input from user
Display message on screen
Display_Msg
Defining Functions-3

Main Fct

AND return control to Main


Invoke to display message AND send
the grade returned by Read_Grade
Display_Message(int g){
For each function decide on:
Possible Parameter List
Possible Return Value

Read_Grade(){

void
int

}



12
Defining Functions (cont.)-3
13

Main Fct

Read_Grade Display_Msg

#include <iostream>
using namespace std;

int main()
{ Read_Grade
int grade;

cout<<"Enter your grade:\n";


cin>>grade;

if (grade>60) cout<<"You passed";


else cout<<“You failed";
Display_Msg
return 0;
}
Defining Functions (cont.)-3
14

int Read_Grade()
{
int grade;
//grade is a local variable
cout<<"Enter your grade:\n";
cin>>grade; grade scope

return grade;
}

void Display_Msg(int g)
{
if (g>60) cout<<"You passed"; g scope
else cout<<“You failed";
}
Using Functions-4
15

#include <iostream>
using namespace std;
// ====== You Must Define your Modules before Main ======
int Read_Grade()
{
int grade;
//grade is a local variable
cout<<"Enter your grade:\n";
cin>>grade;

return grade;
}
void Display_Msg(int g)
{
if (g>60) cout<<"You passed";
else cout<<“You failed";
}
// ====================== Main Fct ======================
int main()
{
// Invoke read module and store returned input
// Invoke display module and pass the grade
return 0;
}
Using Functions (cont.)-4
16

 In our example, all invokations occur in main function.


 Invoking C++ functions syntax:
 Write function name followed by ().
 Within ( ) passing values (arguments) to parameters.
 Functions could have
 No parameters  FunctionName()
 One or more parameters  FunctionName(v1,v2)

 Capturing returned values


 Functions return type could be
 void  FunctionName() OR FunctionName(v1,v2)
 Non-void  must use returned value in expression.
Using Functions (cont.)-4
17

 Capturing returned values


 Non-void  must use returned value in expression

 Function Read_grade() returns an int

 int n = Read_Grade();

 if ( Read_Grade() == 3 ) …… … …

 cout << Read_Grade();


Using Functions (cont.)-4
18

 Each value passed in a function call is referred to as an Argument.


 Arguments (Passed in a Function call) and parameters (defined in a
function header) MUST match in:
 Number
 Order
 Data types
Parameter

void Display_Msg(int g) int main() Argument


{ {
if (g > 60)
cout<<"You passed"; Display_Msg(87);
else
cout<<“You failed"; return 0;
} }
Final Solution
19

#include <iostream>
using namespace std;
// ====== You Must Define your Modules before Main ======
int Read_Grade()
{
int grade;
//grade is a local variable
cout<<"Enter your grade:\n";
cin>>grade;

return grade;
}
void Display_Msg(int g)
{
if (g>60) cout<<"You passed";
else cout<<“You failed";
}
// ====================== Main Fct ======================
int main()
{
int n = Read_Grade(); // Invoke read function
Display_Msg(n); // Invoke display function
return 0;
}
Using Library Functions
20

 Need to know the points below to write invokation of built-in functions


correctly:
 Name of the function.
 Number , type and order of parameters.
 Type of return value if it has.
 Header file.

 Examples
Header File Function call Example Value
<cmath> pow(x,y) pow(2,3) 8
<iomanip> setprecision(n) setprecision(2)<< 1.2345 1.23
Function Prototype
21

 Consists of the function's return type, name and parameter list


(number, types and order of parameters).
 Also called function declaration.

 Usually placed at the top of the program to tell the compiler that the
function exists.

 Same as corresponding function header except that:


 Parameter names are optional
 Must end with a semicolon ;
Examples
22

int square( int x )


{ int square( int );

return x * x;
}

void useLocal( void )


{
int x = 25; void useLocal();

cout << "\nlocal x is " << x << endl;


x++;
cout << "local x is " << x << endl;
}
Compilation Error
23

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

int main()
{
int a = 10;
cout << a << " squared: " << square( a ) << endl;
return 0;
} Error: function undeclared before use
'square': identifier not found
int square( int x )
{
return x * x;
}
Solution -1
24

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

int square( int x )


{
return x * x;
}

int main()
{
int a = 10;
cout << a << " squared: " << square( a ) << endl;
return 0;
}
Solution -2
25

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

int square( int ); // prototype for function square

int main()
{
int a = 10;

cout << a << " squared: " << square( a ) << endl;
return 0;
}

int square( int x )


{
return x * x;
}
Empty Parameter Lists
26

 Specified by writing either void or nothing at all in parentheses.

int sum(); OR int sum(void);


Scope
27

 Identifiers
 Variable or object.
 Function.

 Scope of Identifier
 Portion of the program where an identifier can be used.

 Types of scopes for an identifier:


 Function scope.
 File scope.
 Block scope.
File Scope
28

 For an identifier declared outside any function or class

 Identifier is “known” and can be used in all functions from the point at

which it is declared until the end of the file.

 Examples

 Global variables, function definitions and function prototypes placed

outside a function all have file scope.


Function Scope
29

 Can be used anywhere in the function in which they appear.

 Cannot be referenced outside the function body.

 Examples

 Local variables and function parameters.


Block Scope
30

 Blocks are defined by the beginning left brace ( { ) and the

terminating right brace ( } ).

 Identifiers declared inside a block have block scope

 Block scope begins at the identifier’s declaration.

 Block scope ends at the terminating right brace (}) of the block in which

the identifier is declared.


#include <iostream> File Scope (defined outside any class or function)
using std::cout;
using std::endl;

int x = 1; // global variable


Function / Outer Block Scope (can be used only inside the outer
int main() block defined in Main)
{
int x = 5; // local variable to main

cout << "local x in main's outer scope is " << x << endl;

{ // start new scope


int x = 7; // hides x in outer scope

cout << "local x in main's inner scope is " << x << endl;
} // end new scope

cout << "local x in main's outer scope is " << x << endl;

return 0;
}
Function / Inner Block Scope (can be used only
inside the inner block defined in Main)

31
Function Signature
32

 The portion of a function prototype that includes the name of the


function and the types of parameters.
 Does not specify the function’s return type.

int square( int ); Function Signature


Function Prototype

 Functions in the same scope must have unique signatures.


Compilation Error -1
33

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

int square( int x ) • Two functions in the global(file) scope


{ • They have the same signature:
return x * x; square(int)
} • This results in a compilation error:
'square' : redefinition
void square( int x)
{
cout<< x * x;
}

int main()
{
return 0;
} // end main
Compilation Error -2
34

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

class Num {

int square( int x )


{
• Two functions in the class scope
return x * x;
• They have the same signature:
}
square(int)
void square( int x) • This results in a compilation error
{ 'Num::square' : redefinition
cout<< x * x;
}
};
int main()
{
return 0; // indicate successful termination
} // end main
Compilation Error -3
35

 Arguments (in function call) and parameters (in function header)


must match in Number, Order, and Data Types.
#include <iostream>
using namespace std;

int boxVolume( int length, int width, int height )


{
return length * width * height;
}

int main() {

cout<< boxVolume(); // Error#1: 'boxVolume' : function does not take 0 arguments


cout<< boxVolume(10); // Error#2: 'boxVolume' : function does not take 1 argument
cout<< boxVolume(10,5); // Error#3: 'boxVolume' : function does not take 2 arguments
cout<< boxVolume(10,5,2);
return 0;
}
Argument
36

 Arguments (in function call) and parameters (in function header)


must match in Number, Order, and Data Types.

 Promotion/Demotion may occur when the type of a function


argument does not match the specified parameter type.
Argument Demotion -1
37

#include <iostream>
using namespace std;

int boxVolume( int length, int width , int height ) ;

int main() { Warning: 'argument' :


conversion from 'double'
cout<< boxVolume(10.5,5.7,2.4); to 'int', possible loss
return 0; of data
}

int boxVolume( int length , int width , int height )


{
return length * width * height;
}
Argument Promotion -2
38

#include <iostream>
using namespace std;

void boxVolume( double length, double width , double height ) ;

int main() { No Warning is issued


when promotion of
boxVolume(10,5,2); arguments occurs
return 0;
}

void boxVolume(double length , double width , double height )


{
cout<< length * width * height;
}
Return Type Demotion -3
39

#include <iostream>
using namespace std;

double boxVolume( double length, double width , double height ) ;

int main() { warning : conversion


from 'double' to 'int',
int r = boxVolume(10.5,5.7,2.3); possible loss of data
return 0;
}

double boxVolume(double length , double width , double height )


{
return length * width * height;
}
Return Type Promotion -4
40

#include <iostream>
using namespace std;

int boxVolume( int length, int width , int height ) ;

int main() { No Warning is issued


when promotion of return
double r = boxVolume(10,5,2); values occurs
return 0;
}

int boxVolume(int length , int width , int height )


{
return length * width * height;
}
Function Overloading
41

 Creating several functions of the same name that perform similar


tasks, but on different data types.

 Overloaded functions have:


 Same name.
 Different signature.

 Compiler selects proper function to execute based on number,


types and order of arguments in the function call.
#include <iostream>
using std::cout;
using std::endl;

// function square for int values


int square( int x )
{
cout << "square of integer " << x << " is ";
return x * x;
}

// function square for double values


double square( double y )
{
cout << "square of double " << y << " is ";
return y * y;
}

int main()
{
cout << square( 7 ); // calls int version
cout << endl;
cout << square( 7.5 ); // calls double version
cout << endl;
return 0;
}

42
#include <iostream>
using std::cout;
using std::endl;

// function multiply for two parameters


int multi( int x, int y )
{
return x * y;
}

// function multiply for one parameter


int multi( int y )
{
return y * 1;
}

int main()
{
cout << multi( 7,5 ); // calls 2
parameter version
cout << endl;
cout << multi( 7 ); // calls 1 parameter
version
cout << endl;
return 0;
}
43
#include <iostream>
using std::cout;
using std::endl;

// function multiply for two parameters


int multi( int x, double y )

{
return x * y;
}

// function multiply for two parameter but with


different order
double multi( double y , int x)
{
return y * x;
}

int main()
{
cout << multi( 7,5.5 ); // calls
int,double version
cout << endl;
cout << multi( 7.5,3 ); // calls
double,int version
cout << endl;
return 0;
}
44
Reference Variables
45

grab
memory for

a
// create an integer
an integer
int a ; and labels it
as "a"

// Now create another name for


the // same integer

int& b = a ;
//OR
"b" is just
Int &b = a ;
another label

b
for the same
b is a "reference".
memory
int& means "make a label to reference an integer"

a and b are synonyms for the same thing


Reference Variables (cont.)
46

 Can be used as aliases for other variables


 An alias is simply another name for the original variable

 All operations supposedly performed on the alias (i.e., the


reference) are actually performed on the original variable

 Must be initialized in their declarations


 Cannot be reassigned afterward

 Example count

int count = 1; 1
count
int &cRef = count; 1 cRef
count
cRef++; cRef
2
#include <iostream> Example #1
using std::cout;
using std::endl;
x=3
int main()
{ y=3
int x = 3; x=7
int &y = x; // y refers to (is an alias for) x
y=7
cout << "x = " << x << endl << "y = " << y << endl;
y = 7; // actually modifies x
cout << "x = " << x << endl << "y = " << y << endl;
return 0; // indicates successful termination
} // end main

#include <iostream> Example #2


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

int main()
{
int x = 3;
int &y; // Error: y must be initialized

cout << "x = " << x << endl << "y = " << y << endl;
y = 7;
cout << "x = " << x << endl << "y = " << y << endl;
return 0;
}

47
Passing Arguments
48

 Two ways to pass arguments to functions


 Pass-by-value
 A copy of the argument’s value is passed to the called function
 Changes to the copy do not affect the original variable’s value in the
caller
 Prevents accidental side effects of functions

 Pass-by-reference
 Gives called function the ability to access and modify the caller’s
argument data directly
Reference Parameter
49

 An alias for its corresponding argument in a function call

 & placed after the parameter type in the function prototype and
function header

 Example

void squareByReference( int &numberRef ) ;

 Parameter name in the body of the called function actually refers to


the original variable in the calling function
Pass By Value
50

#include <iostream>
using std::cout;
using std::endl;

int squareByValue( int ); // function prototype (value


pass)

int main() x
{
int x = 2; 2
// demonstrate squareByValue
cout << "x = " << x << " before squareByValue\n";
cout << "Value returned by squareByValue: "
<< squareByValue( x ) << endl;
cout << "x = " << x << " after squareByValue\n" << endl;

return 0;
} number
int squareByValue( int number )
{ 2
return number *= number; // caller's argument not modified
}
Pass By Reference
51

#include <iostream>
using std::cout;
using std::endl;

int squareByReference( int& ); // function prototype (value


pass)

int main()
z
{
int z = 4; 4 numberRef

// demonstrate squareByReference
cout << "z = " << z << " before squareByReference" << endl;

squareByReference( z );
cout << "z = " << z << " after squareByReference" << endl;

return 0;
}
void squareByReference( int &numberRef ) {
numberRef *=
numberRef; // caller's argument modified }
Common Errors
52

 Compilation errors
 Declaring function has parameters of the same type as char a,b instead of
char a, char b.
 Invoking function before it is defined, e.g. when f1 invokes f2, f2 must be
defined before f1.
 Attempting to use a function that has no return value in an expression.

 Two functions in the same scope have the same signature.


 Mismatching function header with function call OR function header with
function prototype in the number, type and order of parameters and
arguments.

You might also like