SlideShare a Scribd company logo
Functions in C++
Outline














Introduction
Standard library in a programming language
C++ Header files
String and character related fuctions
Mathematical functions
Console I/O operations
Other fuctions
Fuction statistics
Types of functions
Function definition
Accesing a function
Returning from a function
Scope rules
Introduction
Functions allow to structure programs in segments
of code to perform individual tasks.
In C++, a function is a group of statements that is
given a name, and which can be called from
some point of the program. The most common
syntax to define a function is:
type name ( parameter1, parameter2, ...) {
statements }
Standard Library in a
Programming Language
 The C++ standard consists of two parts: the core language

and the C++ Standard Library; which C++ programmers
expect on every major implementation of C++, it
includes vectors, lists, maps,algorithms
(find, for_each, binary_search, random_shuffle, etc.), sets,
queues, stacks, arrays, tuples, input/output facilities
(iostream; reading from the console input, reading/writing
from files),smart pointers for automatic memory
management, regular expression support, multi-threading
library, atomics support (allowing a variable to be read or
written to be at most one thread at a time without any
external synchronisation), time utilities
(measurement, getting current time, etc.), a system for
converting error reporting that doesn't use
C++ exceptions into C++ exceptions, a random number
generator and a slightly modified version of the C standard
library (to make it comply with the C++ type system).
 A large part of the C++ library is based on the STL .This provides

useful tools as containers (for example vectors and lists), iterators to
provide these containers with array-like access andalgorithms to
perform operations such as searching and sorting. Furthermore
(multi)maps (associative arrays) and (multi)sets are provided, all of
which export compatible interfaces. Therefore it is possible, using
templates, to write generic algorithms that work with any container
or on any sequence defined by iterators. As in C, the features of
the library are accessed by using the#include directive to include
a standard header. C++ provides 105 standard headers, of which 27
are deprecated.
 The standard incorporates the STL was originally designed
by Alexander Stepanov, who experimented with generic algorithms
and containers for many years. When he started with C++, he finally
found a language where it was possible to create generic algorithms
(e.g., STL sort) that perform even better than, for example, the C
standard library qsort, thanks to C++ features like using inlining and
compile-time binding instead of function pointers. The standard
does not refer to it as "STL", as it is merely a part of the standard
library, but the term is still widely used to distinguish it from the rest
of the standard library (input/output
streams, internationalization, diagnostics, the C library subset, etc.).
 Most C++ compilers, and all major ones, provide a standards
conforming implementation of the C++ standard library.
Function Definition











The general form of a C++ function definition is as follows:
return_type function_name( parameter list ) { body of the function }A
C++ function definition consists of a function header and a function
body. Here are all the parts of a function:
Return Type: A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the
desired operations without returning a value. In this case, the
return_type is the keyword void.
Function Name: This is the actual name of the function. The function
name and the parameter list together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is
invoked, you pass a value to the parameter. This value is referred to as
actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.
Function Body: The function body contains a collection of statements
that define what the function does.
Function Declarations:
 A function declaration tells the compiler about a function





name and how to call the function. The actual body of the
function can be defined separately.
A function declaration has the following parts:
return_type function_name( parameter list );For the above
defined function max(), following is the function
declaration:
int max(int num1, int num2);Parameter names are not
importan in function declaration only their type is
required, so following is also valid declaration:
int max(int, int);Function declaration is required when you
define a function in one source file and you call that
function in another file. In such case, you should declare the
function at the top of the file calling the function.
Calling a Function:
 While creating a C++ function, you give a definition

of what the function has to do. To use a function, you
will have to call or invoke that function.
 When a program calls a function, program control is
transferred to the called function. A called function
performs defined task and when its return statement
is executed or when its function-ending closing
brace is reached, it returns program control back to
the main program.
 To call a function, you simply need to pass the
required parameters along with function name, and
if function returns a value, then you can store
returned value.
Function Arguments:













If a function is to use arguments, it must declare variables that accept the values
of the arguments. These variables are called the formal parameters of the
function.
The formal parameters behave like other local variables inside the function and
are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a
function:
Call TypeDescription
Call by valueThis method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter inside
the function have no effect on the argument.
Call by pointerThis method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the actual argument
used in the call. This means that changes made to the parameter affect the
argument.
Call by referenceThis method copies the reference of an argument into the
formal parameter. Inside the function, the reference is used to access the actual
argument used in the call. This means that changes made to the parameter
affect the argument.By default, C++ uses call by value to pass arguments.
In general, this means that code within a function cannot alter the arguments
used to call the function and above mentioned example while calling max()
function used the same method.
Default Values for Parameters:
 When you define a function, you can specify a
default value for each of the last parameters.
This value will be used if the corresponding

argument is left blank when calling to the
function.
 This is done by using the assignment operator
and assigning values for the arguments in the
function definition. If a value for that parameter
is not passed when the function is called, the
default given value is used, but if a value is
specified, this default value is ignored and the
passed value is used instead.
About Functions in C++
 Functions invoked by a function–call-statement which consist

of it’s name and information it needs (arguments)
 Boss To Worker Analogy
 A Boss (the calling/caller function) asks a worker (the called
function) to perform a task and return result when it is done.
Boss
Main
Worker
Worker

Worker

Function A

Function B

Worker

Function B1

Worker

Function B2

Function Z
Note: usual main( ) Calls other
functions, but other functions can
call each other
Function Calling
• Functions

called by writing

functionName (argument);
or

functionName(argument1, argument2, …);
• Example
cout << sqrt( 900.0 );
• sqrt (square root) function

• The preceding statement would print 30
• All functions in math library return a double


-

Function Arguments can be:
Constant
sqrt(9);
Variable
sqrt(x);
Expression
sqrt( x*9 + y) ;
sqrt( sqrt(x) ) ;
Function Calling
• Calling/invoking a function
– sqrt(x);
– Parentheses an operator used to call function
• Pass argument x
• Function gets its own copy of arguments
– After finished, passes back result
Function Name

cout<< sqrt(9);

Output

argument

3

Parentheses used to enclose argument(s)
Math Library Functions Revisited
Method
ceil( x )

exp( x )

Description
rounds x to the smallest integer
not less than x
trigonometric cosine of x
(x in radians)
exponential function ex

fabs( x )

absolute value of x

floor( x )

log( x )

rounds x to the largest integer
not greater than x
remainder of x/y as a floatingpoint number
natural logarithm of x (base e)

log10( x )

logarithm of x (base 10)

pow( x, y )

x raised to power y (xy)

sin( x )

trigonometric sine of x
(x in radians)
square root of x

cos( x )

fmod( x, y )

sqrt( x )
tan( x )

trigonometric tangent of x
(x in radians)
Fig. 3.2 Math library functions.

Example
ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0
cos( 0.0 ) is 1.0
exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
fabs( 5.1 ) is 5.1
fabs( 0.0 ) is 0.0
fabs( -8.76 ) is 8.76
floor( 9.2 ) is 9.0
floor( -9.8 ) is -10.0
fmod( 13.657, 2.333 ) is 1.992
log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
pow( 2, 7 ) is 128
pow( 9, .5 ) is 3
sin( 0.0 ) is 0
sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( 0.0 ) is 0
Function Definition
• Example function
int square( int y )
{
return y * y;
}

• return keyword
– Returns data, and control goes to function’s caller
• If no data to return, use return;

– Function ends when reaches right brace
• Control goes to caller

• Functions cannot be defined inside other
functions
// Creating and using a programmer-defined function.
#include <iostream.h>
int square( int );

// function prototype

Function prototype: specifies
data types of arguments and
return values. square
expects an int, and returns
an int.

int main()
{
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " "; // function call

Parentheses () cause function to be called.
When done, it returns the result.

cout << endl;
return 0;

// indicates successful termination

} // end main

// square function definition returns square of an integer
int square( int y ) // y is a copy of argument to function
{
Definition
return y * y;
// returns square of y as an int

of square. y is a
copy of the argument passed.
Returns y * y, or y squared.

} // end function square

1

4

9

16

25

36

49

64

81

100
compute square and cube of numbers [1..10] using functions
#include<iostream.h>
int square(int); // prototype
int cube(int);
// prototype
main()
{ int i;
for (int i=1;i<=10;i++){
cout<< i<< “square=“ << square(i) << endl;
cout<< i<< “cube=“
<<cube(i) << endl;
} // end for
return 0;
} // end main function
int square(int y) //function definition
{
return y*y; // returned Result
}
int cube(int y) //function definition
{
return y*y*y; // returned Result
}

Output
1 square=1
1 cube=1
2 square=4
2 cube=8
.
.
.
.
10 square=100
10 cube=1000
Function Prototypes


Function prototype contains







Function name
Parameters (number and data type)
Return type (void if returns nothing)
Only needed if function definition after function call

Prototype must match function definition


Function prototype
double maximum( double, double, double );



Definition
double maximum( double x, double y, double
z )
{
…
}
void Function takes arguments
If the Function does not RETURN result, it is called void
Function
#include<iostream.h>
void add2Nums(int,int);
main()
{
int a, b;
cout<<“enter tow Number:”;
cin >>a >> b;
add2Nums(a, b)
return 0;
}
void add2Nums(int x, int y)
{
cout<< x<< “+” << y << “=“ << x+y;
}
void Function take no arguments
If the function Does Not Take Arguments specify this with EMPTY-LIST OR
write void inside
#include<iostream.h>
void funA();
void funB(void)
main()
Will be the same
{
funA();
in all cases
funB();
return 0;
}
void funA()
{
cout << “Function-A takes no arqumentsn”;
}
void funB()
{
cout << “Also Function-B takes No argumentsn”;
}
Remarks on Functions


Local variables





Parameters




Known only in the function in which they are defined
All variables declared inside a function are local variables

Local variables passed to function when called (passingparameters)

Variables defined outside and before function main:




Called global variables
Can be accessible and used anywhere in the entire
program
Remarks on Functions


Omitting the type of returned result defaults to int, but
omitting a non-integer type is a Syntax Error



If a Global variable defined again as a local variable in a
function, then the Local-definition overrides the Global
defining



Function prototype, function definition, and function call
must be consistent in:
1- Number of arguments
2- Type of those arguments
3-Order of those arguments
Local vs Global Variables
#include<iostream.h>
int x,y; //Global Variables
int add2(int, int); //prototype
main()
{ int s;
x = 11;
y = 22;
cout << “global x=” << x << endl;
cout << “Global y=” << y << endl;
s = add2(x, y);
cout << x << “+” << y << “=“ << s;
cout<<endl;
cout<<“n---end of output---n”;
return 0;
}
int add2(int x1,int y1)
{ int x; //local variables
x=44;
cout << “nLocal x=” << x << endl;
return x1+y1;
}

global x=11
global y=22
Local x=44
11+22=33
---end of output---
Finding Errors in Function Code
int sum(int x, int y)
{
int result;
result = x+y;
}
this function must return an integer value as indicated in the
header definition (return result;) should be added
---------------------------------------------------------------------------------------int sum (int n)
{ if (n==0)
return 0;
else
n+sum(n-1);
}
the result of n+sum(n-1) is not returned; sum returns an
improper result, the else part should be written as:else return n+sum(n-1);
Finding Errors in Function Code
void f(float a);
{
float a;
cout<<a<<endl;
}


; found after function definition header.

redefining the parameter a in the function
void f(float a)
{
float a2 = a + 8.9;
cout <<a2<<endl;
}

Finding Errors in Function Code
void product(void)
{
int a, b, c, result;
cout << “enter three integers:”;
cin >> a >> b >> c;
result = a*b*c;
cout << “Result is” << result;
return result;
}

According to the definition it should not return a value , but in the block
(body) it did & this is WRONG.

 Remove return Result;
Function Call Methods
Call by value



•

A copy of the value is passed

Call by reference



•

The caller passes the address of the value



Call by value



Up to this point all the calls we have seen are call-by-value, a copy
of the value (known) is passed from the caller-function to the calledfunction
Any change to the copy does not affect the original value in the
caller function
Advantages, prevents side effect, resulting in reliable software




Function Call Methods


Call By Reference



We introduce reference-parameter, to perform call by reference. The caller
gives the called function the ability to directly access the caller’s value, and
to modify it.
A reference parameter is an alias for it’s corresponding argument, it is stated
in c++ by “flow the parameter’s type” in the function prototype by an
ampersand(&) also in the function definition-header.
Advantage: performance issue





void

function_name (type &);// prototype

main()
{
---------}
void function_name(type &parameter_name)
Function Call Example
#include<iostream.h>
int squareVal(int); //prototype call by value function
void squareRef(int &); // prototype call by –reference function
int main()
{ int x=2; z=4;
cout<< “x=“ << x << “before calling squareVal”;
cout << “n” << squareVal(x) << “n”; // call by value
cout<< “x=“ << x << “After returning”
cout<< “z=“ << z << “before calling squareRef”;
squareRef(z); // call by reference
cout<< “z=“ << z<< “After returning squareRef”
return 0;
x=2 before calling squareVal
}
4
int squareVal(int a)
x=2 after returning
{
z=4 before calling squareRef
return a*=a; // caller’s argument not modified
z=16 after returning squareRef
}
void squarRef(int &cRef)
{
cRef *= cRef; // caller’s argument modified
}
Random Number Generator


rand function generates an integer between 0 and RAND-



MAX(~32767) a symbolic constant defined in <stdlib.h>
You may use modulus operator (%) to generate numbers within a
specifically range with rand.

//generate 10 random numbers open-range
int x;
for( int i=0; i<=10; i++){
x=rand();
cout<<x<<“ “;
}

------------------------------------------------------//generate 10 integers between 0……..49
int x;
for( int i=0; i<10; i++){
x=rand()%50;
cout<<x<<“ “;
}
Random Number Generator
//generate 10 integers between 5…15
int x;
for ( int i=1; i<=10; i++){
x= rand()%11 + 5;
cout<<x<<“ “;
}
------------------------------------

//generate 100 number as simulation of rolling a
dice
int x;
for (int i=1; i<=100; i++){
x= rand%6 + 1;
cout<<x<<“ “;
}
Random Number Generator




the rand( ) function will generate the same set of
random numbers each time you run the program .
To force NEW set of random numbers with each new
run use the randomizing process
Randomizing is accomplished with the standard library
function srand(unsigned integer); which needs a
header file <stdlib.h>

Explanation of signed and unsigned integers:
 int is stored in at least two-bytes of memory and can
have positive & negative values
 unsigned int also stored in at least two-bytes of
memory but it can have only positive values 0…..65535
Randomizing with srand
#include<iostream.h>
#include<iomanip.h>
#include<stdlib.h>
int main()
{
int i;
unsigned num;
// we will enter a different number each time we run
cin>>num;
srand(num);
for(i=1; i<=5; i++)
cout<<setw(10)<< 1+rand()%6;
return 0;
}

Output for Multiple Runs
19
18
3
0
3

6
6
1
1
1

1
1
2
5
2

1
5
5
5
5

4
1
6
3
6

2
4
2
5
3

1
4
4
5
4

Different-set of Random
numbers
without srand
#include<iostream.h>
#include<iomanip.h>
#include<stdlib.h>

int main()
{
int i;
for(i=1; i<=5; i++)
cout<<setw(10)<< 1+rand()%6;
return 0;
}

Output for Multiple Runs
5
5
5
5
6

3
3
3
3
5

3
3
3
3
3

5
5
5
5
3

4
4
4
4
5

2
2
2
2
4

Same set of numbers for
each run
Function Overloading


Function overloading
Functions with same name and different parameters
 Should perform similar tasks


 I.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }


A call-time c++ complier selects the proper function by
examining the number, type and order of the parameters
C++ Variables
• A variable is a place in memory that has
–
–
–
–

A name or identifier (e.g. income, taxes, etc.)
A data type (e.g. int, double, char, etc.)
A size (number of bytes)
A scope (the part of the program code that can use it)
• Global variables – all functions can see it and using it
• Local variables – only the function that declare local variables see
and use these variables

– A life time (the duration of its existence)
• Global variables can live as long as the program is executed
• Local variables are lived only when the functions that define these
variables are executed

36
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

37
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

x

0

38
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

x

1

0

void main()
{
f2();
cout << x << endl ;
}
39
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

x

4
0

2

void f2()
{
x += 4;
f1();
}

1

void main()
{
f2();
cout << x << endl ;
}
40
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

x

4

3

1

5
4
void f1()
{
x++;
}
void f2()
{
x += 4;
f1();
}
void main()
{
f2();
cout << x << endl ;
}
41
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

x

5

3

1

5
4
void f1()
{
x++;
}
void f2()
{
x += 4;
f1();
}
void main()
{
f2();
cout << x << endl;
}
42
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

x

6

1

5
4

void f2()
{
x += 4;
f1();
}
void main()
{
f2();
cout << x << endl;
}
43
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

x

7

5
4

void main()
{
f2();
cout << x << endl;
}
44
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

x

8

5
4

void main()
{
f2();
cout << x << endl;
}
45
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
46
What is Bad About Using
Global Vairables?
• Not safe!
– If two or more programmers are working together in a
program, one of them may change the value stored in the
global variable without telling the others who may depend
in their calculation on the old stored value!

• Against The Principle of Information Hiding!
– Exposing the global variables to all functions is against
the principle of information hiding since this gives all
functions the freedom to change the values stored in the
global variables at any time (unsafe!)

47
Local Variables
• Local variables are declared inside the function
body and exist as long as the function is running
and destroyed when the function exit
• You have to initialize the local variable before using
it
• If a function defines a local variable and there was a
global variable with the same name, the function
uses its local variable instead of using the global
variable

48
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
49
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature

x

0

Global variables are
automatically initialized to 0

void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
50
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature

x

0

void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}

1

void main()
{
x = 4;
fun();
cout << x << endl;
}

51
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}

4

x

void fun()
x

????

{
int x = 10;
cout << x << endl;

3
}

2

void main()
{
x = 4;
fun();
cout << x << endl;
}

52
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}

4

x

void fun()
x

10

{
int x = 10;
cout << x << endl;

3
}

2

void main()
{
x = 4;
fun();
cout << x << endl;
}

53
Example of Defining and Using
Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}

4

x

void fun()
x

10

{
int x = 10;
cout << x << endl;

4

}

2

void main()
{
x = 4;
fun();
cout << x << endl;
}

54
Example of Defining and Using
Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}

4

x

void fun()
x

10

{
int x = 10;
cout << x << endl;
5

2

}
void main()
{
x = 4;
fun();
cout << x << endl;
}

55
Example of Defining and Using
Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature

x

4

void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
6

void main()
{
x = 4;
fun();
cout << x << endl;
}

56
Example of Defining and Using
Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature

x

4

void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}

7

void main()
{
x = 4;
fun();
cout << x << endl;
}

57
II. Using Parameters
• Function Parameters come in three
flavors:
– Value parameters – which copy the
values of the function arguments
– Reference parameters – which refer to
the function arguments by other local
names and have the ability to change
the values of the referenced arguments
– Constant reference parameters – similar
to the reference parameters but cannot
58
change the values of the referenced
Value Parameters
• This is what we use to declare in the function signature or
function header, e.g.

int max (int x, int y);
– Here, parameters x and y are value parameters
– When you call the max function as max(4, 7), the values 4 and 7
are copied to x and y respectively
– When you call the max function as max (a, b), where a=40 and
b=10, the values 40 and 10 are copied to x and y respectively
– When you call the max function as max( a+b, b/2), the values 50
and 5 are copies to x and y respectively

• Once the value parameters accepted copies of the
corresponding arguments data, they act as local
variables!
59
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

x

1

0

void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

60
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

x

3

2

4

void fun(int x
)
{
cout << x << endl;
x=x+5;
}
void main()
{
3
x = 4;
fun(x/2+1);
cout << x << endl;
}

61
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

x

4

2

4

void fun(int x 3 )
8
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

62
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

x

5

2

4

void fun(int x 3 )
8
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

63
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

x

6

4

void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

64
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

x

7

4

void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

65
Reference Parameters
• As we saw in the last example, any changes in the
value parameters don’t affect the original function
arguments
• Sometimes, we want to change the values of the
original function arguments or return with more than
one value from the function, in this case we use
reference parameters
– A reference parameter is just another name to the original
argument variable
– We define a reference parameter by adding the & in front
of the parameter name, e.g.

double update (double & x);
66
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x = 4; // Local variable
fun(x);
cout << x << endl;
}

1

void main()
{
4
?
int x = 4;
fun(x);
cout << x << endl;
}

x

67
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x = 4; // Local variable
fun(x);
cout << x << endl;
}

3

2

void fun( int & y
{
cout<<y<<endl;
y=y+5;
}
void main()
{
4
?
int x = 4;
fun(x);
cout << x << endl;
}

)

x

68
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x = 4; // Local variable
fun(x);
cout << x << endl;
}

4

2

void fun( int & y
{
cout<<y<<endl;
y=y+5;
9
}
void main()
{
4
?
int x = 4;
fun(x);
cout << x << endl;
}

)

x

69
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x = 4; // Local variable
fun(x);
cout << x << endl;
}

5

2

void fun( int & y
{
cout<<y<<endl;
y=y+5;
}
void main()
{
9
?
int x = 4;
fun(x);
cout << x << endl;
}

)

x

70
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x = 4; // Local variable
fun(x);
cout << x << endl;
}

6

void main()
{
9
?
int x = 4;
fun(x);
cout << x << endl;
}

x

71
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x = 4; // Local variable
fun(x);
cout << x << endl;
}
7

void main()
{
9
?
int x = 4;
fun(x);
cout << x << endl;
}

x

72
Constant Reference Parameters
• Constant reference parameters are used under
the following two conditions:
– The passed data are so big and you want to save
time and computer memory
– The passed data will not be changed or updated in
the function body

• For example
void report (const string & prompt);
• The only valid arguments accepted by reference
parameters and constant reference parameters
are variable names
– It is a syntax error to pass constant values or
expressions to the (const) reference parameters
73
Header Files
• Header files
– Contain function prototypes for library
functions
– <stdlib.h> , <math.h> , etc
– Load with #include <filename>
#include <math.h>
• Custom header files
– Create file with functions
– Save as filename.h
– Load in other files with #include
Scope Rules
• File scope
– Identifier defined outside function, known in
all functions
– Used for global variables, function
definitions, function prototypes
• Function scope
– Can only be referenced inside a function
body
– Used only for labels (start:, case:
, etc.)
Scope Rules
• Block scope
– Identifier declared inside a block
• Block scope begins at declaration, ends
at right brace
– Used for variables, function parameters
(local variables of function)
– Outer blocks "hidden" from inner blocks if
there is a variable with the same name in
the inner block
• Function prototype scope
Thank You

More Related Content

What's hot (18)

PPT
Lecture#6 functions in c++
NUST Stuff
 
PPT
Functions in C++
Mohammed Sikander
 
PPT
C++ functions
Dawood Jutt
 
ODP
Function
jayesh30sikchi
 
PPT
Function overloading(C++)
Ritika Sharma
 
PPT
Functions in C++
Nikhil Pandit
 
PPTX
functions of C++
tarandeep_kaur
 
PDF
Functions
Pragnavi Erva
 
PPTX
Function in c
CGC Technical campus,Mohali
 
PDF
Functions in C++
Pranali Chaudhari
 
PPT
Functions in C++
Sachin Sharma
 
PPTX
Parameter passing to_functions_in_c
ForwardBlog Enewzletter
 
PPTX
Functions in c++
HalaiHansaika
 
PPTX
Learning C++ - Functions in C++ 3
Ali Aminian
 
PPTX
Call by value or call by reference in C++
Sachin Yadav
 
PPTX
Function in c++
Kumar
 
PPTX
Function in c program
umesh patil
 
PDF
03 function overloading
Jasleen Kaur (Chandigarh University)
 
Lecture#6 functions in c++
NUST Stuff
 
Functions in C++
Mohammed Sikander
 
C++ functions
Dawood Jutt
 
Function
jayesh30sikchi
 
Function overloading(C++)
Ritika Sharma
 
Functions in C++
Nikhil Pandit
 
functions of C++
tarandeep_kaur
 
Functions
Pragnavi Erva
 
Functions in C++
Pranali Chaudhari
 
Functions in C++
Sachin Sharma
 
Parameter passing to_functions_in_c
ForwardBlog Enewzletter
 
Functions in c++
HalaiHansaika
 
Learning C++ - Functions in C++ 3
Ali Aminian
 
Call by value or call by reference in C++
Sachin Yadav
 
Function in c++
Kumar
 
Function in c program
umesh patil
 
03 function overloading
Jasleen Kaur (Chandigarh University)
 

Viewers also liked (20)

PPTX
C++ theory
Shyam Khant
 
DOCX
Designing the application
Milind Mishra
 
PPT
Part 3-functions
ankita44
 
PDF
Chapter 10 Library Function
Deepak Singh
 
PPT
Csc1100 lecture06 ch06_pt2
IIUM
 
PPT
Lec 45.46- virtual.functions
Princess Sam
 
PPTX
Vocabulary: Ana & Paloma
anapaloma94
 
PPTX
Project: Ana & Paloma
anapaloma94
 
PPTX
writting skills
Nagendra N
 
DOCX
Type header file in c++ and its function
Frankie Jones
 
PPT
C++ functions
Dawood Jutt
 
PPTX
The Essential School's Guide to Adaptive Learning
Lorna Keane
 
PDF
Character building
W Diana Ratri M.Psi, Psikolog
 
PDF
Basic communication skills
Nana Saidin
 
PPT
C++ programming
Pranav Ghildiyal
 
PDF
Object Oriented Program
Alisha Jain
 
PDF
C++ arrays part2
Subhasis Nayak
 
PPS
Inheritance
Ashish Awasthi
 
C++ theory
Shyam Khant
 
Designing the application
Milind Mishra
 
Part 3-functions
ankita44
 
Chapter 10 Library Function
Deepak Singh
 
Csc1100 lecture06 ch06_pt2
IIUM
 
Lec 45.46- virtual.functions
Princess Sam
 
Vocabulary: Ana & Paloma
anapaloma94
 
Project: Ana & Paloma
anapaloma94
 
writting skills
Nagendra N
 
Type header file in c++ and its function
Frankie Jones
 
C++ functions
Dawood Jutt
 
The Essential School's Guide to Adaptive Learning
Lorna Keane
 
Character building
W Diana Ratri M.Psi, Psikolog
 
Basic communication skills
Nana Saidin
 
C++ programming
Pranav Ghildiyal
 
Object Oriented Program
Alisha Jain
 
C++ arrays part2
Subhasis Nayak
 
Inheritance
Ashish Awasthi
 
Ad

Similar to Functions in C++ (20)

PPTX
Functions in C++
home
 
PPT
Ch4 functions
Hattori Sidek
 
PDF
Cpp functions
NabeelaNousheen
 
PPTX
Functions in Python Programming Language
BeulahS2
 
PPTX
User defined function in C.pptx
Rhishav Poudyal
 
PDF
1.6 Function.pdf
NirmalaShinde3
 
DOC
Functions
zeeshan841
 
PPT
python slides introduction interrupt.ppt
Vinod Deenathayalan
 
PPTX
Python Functions.pptx
AnuragBharti27
 
PPTX
Python Functions.pptx
AnuragBharti27
 
PDF
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
PDF
programlama fonksiyonlar c++ hjhjghjv jg
uleAmet
 
PPT
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
PPT
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
PPTX
c & c++ logic building concepts practice.pptx
rawatsatish0327
 
PPTX
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
vekariyakashyap
 
PPT
Python programming variables and comment
MalligaarjunanN
 
PPTX
Lecture_5_-_Functions_in_C_Detailed.pptx
Salim Shadman Ankur
 
PPTX
Functions in c language
Tanmay Modi
 
Functions in C++
home
 
Ch4 functions
Hattori Sidek
 
Cpp functions
NabeelaNousheen
 
Functions in Python Programming Language
BeulahS2
 
User defined function in C.pptx
Rhishav Poudyal
 
1.6 Function.pdf
NirmalaShinde3
 
Functions
zeeshan841
 
python slides introduction interrupt.ppt
Vinod Deenathayalan
 
Python Functions.pptx
AnuragBharti27
 
Python Functions.pptx
AnuragBharti27
 
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
programlama fonksiyonlar c++ hjhjghjv jg
uleAmet
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
c & c++ logic building concepts practice.pptx
rawatsatish0327
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
vekariyakashyap
 
Python programming variables and comment
MalligaarjunanN
 
Lecture_5_-_Functions_in_C_Detailed.pptx
Salim Shadman Ankur
 
Functions in c language
Tanmay Modi
 
Ad

Recently uploaded (20)

PPTX
MALABSORPTION SYNDROME: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
PPTX
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
PPTX
Top 10 AI Tools, Like ChatGPT. You Must Learn In 2025
Digilearnings
 
PDF
Stepwise procedure (Manually Submitted & Un Attended) Medical Devices Cases
MUHAMMAD SOHAIL
 
PPTX
GENERAL METHODS OF ISOLATION AND PURIFICATION OF MARINE__MPHARM.pptx
SHAHEEN SHABBIR
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
PDF
Module 1: Determinants of Health [Tutorial Slides]
JonathanHallett4
 
PDF
FULL DOCUMENT: Read the full Deloitte and Touche audit report on the National...
Kweku Zurek
 
PPTX
Nutrition Quiz bee for elementary 2025 1.pptx
RichellMarianoPugal
 
PPTX
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
PPTX
Constitutional Design Civics Class 9.pptx
bikesh692
 
PDF
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
PPTX
Rules and Regulations of Madhya Pradesh Library Part-I
SantoshKumarKori2
 
PPTX
YSPH VMOC Special Report - Measles Outbreak Southwest US 7-20-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
PPTX
How to Manage Resupply Subcontracting in Odoo 18
Celine George
 
PPTX
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
PPTX
Qweb Templates and Operations in Odoo 18
Celine George
 
PPTX
national medicinal plants board mpharm.pptx
SHAHEEN SHABBIR
 
PPTX
Unlock the Power of Cursor AI: MuleSoft Integrations
Veera Pallapu
 
PPTX
IDEAS AND EARLY STATES Social science pptx
NIRANJANASSURESH
 
MALABSORPTION SYNDROME: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
Top 10 AI Tools, Like ChatGPT. You Must Learn In 2025
Digilearnings
 
Stepwise procedure (Manually Submitted & Un Attended) Medical Devices Cases
MUHAMMAD SOHAIL
 
GENERAL METHODS OF ISOLATION AND PURIFICATION OF MARINE__MPHARM.pptx
SHAHEEN SHABBIR
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
Module 1: Determinants of Health [Tutorial Slides]
JonathanHallett4
 
FULL DOCUMENT: Read the full Deloitte and Touche audit report on the National...
Kweku Zurek
 
Nutrition Quiz bee for elementary 2025 1.pptx
RichellMarianoPugal
 
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
Constitutional Design Civics Class 9.pptx
bikesh692
 
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
Rules and Regulations of Madhya Pradesh Library Part-I
SantoshKumarKori2
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 7-20-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
How to Manage Resupply Subcontracting in Odoo 18
Celine George
 
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
Qweb Templates and Operations in Odoo 18
Celine George
 
national medicinal plants board mpharm.pptx
SHAHEEN SHABBIR
 
Unlock the Power of Cursor AI: MuleSoft Integrations
Veera Pallapu
 
IDEAS AND EARLY STATES Social science pptx
NIRANJANASSURESH
 

Functions in C++

  • 2. Outline              Introduction Standard library in a programming language C++ Header files String and character related fuctions Mathematical functions Console I/O operations Other fuctions Fuction statistics Types of functions Function definition Accesing a function Returning from a function Scope rules
  • 3. Introduction Functions allow to structure programs in segments of code to perform individual tasks. In C++, a function is a group of statements that is given a name, and which can be called from some point of the program. The most common syntax to define a function is: type name ( parameter1, parameter2, ...) { statements }
  • 4. Standard Library in a Programming Language  The C++ standard consists of two parts: the core language and the C++ Standard Library; which C++ programmers expect on every major implementation of C++, it includes vectors, lists, maps,algorithms (find, for_each, binary_search, random_shuffle, etc.), sets, queues, stacks, arrays, tuples, input/output facilities (iostream; reading from the console input, reading/writing from files),smart pointers for automatic memory management, regular expression support, multi-threading library, atomics support (allowing a variable to be read or written to be at most one thread at a time without any external synchronisation), time utilities (measurement, getting current time, etc.), a system for converting error reporting that doesn't use C++ exceptions into C++ exceptions, a random number generator and a slightly modified version of the C standard library (to make it comply with the C++ type system).
  • 5.  A large part of the C++ library is based on the STL .This provides useful tools as containers (for example vectors and lists), iterators to provide these containers with array-like access andalgorithms to perform operations such as searching and sorting. Furthermore (multi)maps (associative arrays) and (multi)sets are provided, all of which export compatible interfaces. Therefore it is possible, using templates, to write generic algorithms that work with any container or on any sequence defined by iterators. As in C, the features of the library are accessed by using the#include directive to include a standard header. C++ provides 105 standard headers, of which 27 are deprecated.  The standard incorporates the STL was originally designed by Alexander Stepanov, who experimented with generic algorithms and containers for many years. When he started with C++, he finally found a language where it was possible to create generic algorithms (e.g., STL sort) that perform even better than, for example, the C standard library qsort, thanks to C++ features like using inlining and compile-time binding instead of function pointers. The standard does not refer to it as "STL", as it is merely a part of the standard library, but the term is still widely used to distinguish it from the rest of the standard library (input/output streams, internationalization, diagnostics, the C library subset, etc.).  Most C++ compilers, and all major ones, provide a standards conforming implementation of the C++ standard library.
  • 6. Function Definition       The general form of a C++ function definition is as follows: return_type function_name( parameter list ) { body of the function }A C++ function definition consists of a function header and a function body. Here are all the parts of a function: Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature. Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Function Body: The function body contains a collection of statements that define what the function does.
  • 7. Function Declarations:  A function declaration tells the compiler about a function     name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts: return_type function_name( parameter list );For the above defined function max(), following is the function declaration: int max(int num1, int num2);Parameter names are not importan in function declaration only their type is required, so following is also valid declaration: int max(int, int);Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.
  • 8. Calling a Function:  While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function.  When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.  To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value.
  • 9. Function Arguments:         If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. While calling a function, there are two ways that arguments can be passed to a function: Call TypeDescription Call by valueThis method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. Call by pointerThis method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. Call by referenceThis method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.
  • 10. Default Values for Parameters:  When you define a function, you can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function.  This is done by using the assignment operator and assigning values for the arguments in the function definition. If a value for that parameter is not passed when the function is called, the default given value is used, but if a value is specified, this default value is ignored and the passed value is used instead.
  • 11. About Functions in C++  Functions invoked by a function–call-statement which consist of it’s name and information it needs (arguments)  Boss To Worker Analogy  A Boss (the calling/caller function) asks a worker (the called function) to perform a task and return result when it is done. Boss Main Worker Worker Worker Function A Function B Worker Function B1 Worker Function B2 Function Z Note: usual main( ) Calls other functions, but other functions can call each other
  • 12. Function Calling • Functions called by writing functionName (argument); or functionName(argument1, argument2, …); • Example cout << sqrt( 900.0 ); • sqrt (square root) function • The preceding statement would print 30 • All functions in math library return a double  - Function Arguments can be: Constant sqrt(9); Variable sqrt(x); Expression sqrt( x*9 + y) ; sqrt( sqrt(x) ) ;
  • 13. Function Calling • Calling/invoking a function – sqrt(x); – Parentheses an operator used to call function • Pass argument x • Function gets its own copy of arguments – After finished, passes back result Function Name cout<< sqrt(9); Output argument 3 Parentheses used to enclose argument(s)
  • 14. Math Library Functions Revisited Method ceil( x ) exp( x ) Description rounds x to the smallest integer not less than x trigonometric cosine of x (x in radians) exponential function ex fabs( x ) absolute value of x floor( x ) log( x ) rounds x to the largest integer not greater than x remainder of x/y as a floatingpoint number natural logarithm of x (base e) log10( x ) logarithm of x (base 10) pow( x, y ) x raised to power y (xy) sin( x ) trigonometric sine of x (x in radians) square root of x cos( x ) fmod( x, y ) sqrt( x ) tan( x ) trigonometric tangent of x (x in radians) Fig. 3.2 Math library functions. Example ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 cos( 0.0 ) is 1.0 exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906 fabs( 5.1 ) is 5.1 fabs( 0.0 ) is 0.0 fabs( -8.76 ) is 8.76 floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0 fmod( 13.657, 2.333 ) is 1.992 log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0 log10( 10.0 ) is 1.0 log10( 100.0 ) is 2.0 pow( 2, 7 ) is 128 pow( 9, .5 ) is 3 sin( 0.0 ) is 0 sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0 tan( 0.0 ) is 0
  • 15. Function Definition • Example function int square( int y ) { return y * y; } • return keyword – Returns data, and control goes to function’s caller • If no data to return, use return; – Function ends when reaches right brace • Control goes to caller • Functions cannot be defined inside other functions
  • 16. // Creating and using a programmer-defined function. #include <iostream.h> int square( int ); // function prototype Function prototype: specifies data types of arguments and return values. square expects an int, and returns an int. int main() { // loop 10 times and calculate and output // square of x each time for ( int x = 1; x <= 10; x++ ) cout << square( x ) << " "; // function call Parentheses () cause function to be called. When done, it returns the result. cout << endl; return 0; // indicates successful termination } // end main // square function definition returns square of an integer int square( int y ) // y is a copy of argument to function { Definition return y * y; // returns square of y as an int of square. y is a copy of the argument passed. Returns y * y, or y squared. } // end function square 1 4 9 16 25 36 49 64 81 100
  • 17. compute square and cube of numbers [1..10] using functions #include<iostream.h> int square(int); // prototype int cube(int); // prototype main() { int i; for (int i=1;i<=10;i++){ cout<< i<< “square=“ << square(i) << endl; cout<< i<< “cube=“ <<cube(i) << endl; } // end for return 0; } // end main function int square(int y) //function definition { return y*y; // returned Result } int cube(int y) //function definition { return y*y*y; // returned Result } Output 1 square=1 1 cube=1 2 square=4 2 cube=8 . . . . 10 square=100 10 cube=1000
  • 18. Function Prototypes  Function prototype contains      Function name Parameters (number and data type) Return type (void if returns nothing) Only needed if function definition after function call Prototype must match function definition  Function prototype double maximum( double, double, double );  Definition double maximum( double x, double y, double z ) { … }
  • 19. void Function takes arguments If the Function does not RETURN result, it is called void Function #include<iostream.h> void add2Nums(int,int); main() { int a, b; cout<<“enter tow Number:”; cin >>a >> b; add2Nums(a, b) return 0; } void add2Nums(int x, int y) { cout<< x<< “+” << y << “=“ << x+y; }
  • 20. void Function take no arguments If the function Does Not Take Arguments specify this with EMPTY-LIST OR write void inside #include<iostream.h> void funA(); void funB(void) main() Will be the same { funA(); in all cases funB(); return 0; } void funA() { cout << “Function-A takes no arqumentsn”; } void funB() { cout << “Also Function-B takes No argumentsn”; }
  • 21. Remarks on Functions  Local variables    Parameters   Known only in the function in which they are defined All variables declared inside a function are local variables Local variables passed to function when called (passingparameters) Variables defined outside and before function main:   Called global variables Can be accessible and used anywhere in the entire program
  • 22. Remarks on Functions  Omitting the type of returned result defaults to int, but omitting a non-integer type is a Syntax Error  If a Global variable defined again as a local variable in a function, then the Local-definition overrides the Global defining  Function prototype, function definition, and function call must be consistent in: 1- Number of arguments 2- Type of those arguments 3-Order of those arguments
  • 23. Local vs Global Variables #include<iostream.h> int x,y; //Global Variables int add2(int, int); //prototype main() { int s; x = 11; y = 22; cout << “global x=” << x << endl; cout << “Global y=” << y << endl; s = add2(x, y); cout << x << “+” << y << “=“ << s; cout<<endl; cout<<“n---end of output---n”; return 0; } int add2(int x1,int y1) { int x; //local variables x=44; cout << “nLocal x=” << x << endl; return x1+y1; } global x=11 global y=22 Local x=44 11+22=33 ---end of output---
  • 24. Finding Errors in Function Code int sum(int x, int y) { int result; result = x+y; } this function must return an integer value as indicated in the header definition (return result;) should be added ---------------------------------------------------------------------------------------int sum (int n) { if (n==0) return 0; else n+sum(n-1); } the result of n+sum(n-1) is not returned; sum returns an improper result, the else part should be written as:else return n+sum(n-1);
  • 25. Finding Errors in Function Code void f(float a); { float a; cout<<a<<endl; }  ; found after function definition header. redefining the parameter a in the function void f(float a) { float a2 = a + 8.9; cout <<a2<<endl; } 
  • 26. Finding Errors in Function Code void product(void) { int a, b, c, result; cout << “enter three integers:”; cin >> a >> b >> c; result = a*b*c; cout << “Result is” << result; return result; }  According to the definition it should not return a value , but in the block (body) it did & this is WRONG.   Remove return Result;
  • 27. Function Call Methods Call by value  • A copy of the value is passed Call by reference  • The caller passes the address of the value  Call by value  Up to this point all the calls we have seen are call-by-value, a copy of the value (known) is passed from the caller-function to the calledfunction Any change to the copy does not affect the original value in the caller function Advantages, prevents side effect, resulting in reliable software  
  • 28. Function Call Methods  Call By Reference  We introduce reference-parameter, to perform call by reference. The caller gives the called function the ability to directly access the caller’s value, and to modify it. A reference parameter is an alias for it’s corresponding argument, it is stated in c++ by “flow the parameter’s type” in the function prototype by an ampersand(&) also in the function definition-header. Advantage: performance issue   void function_name (type &);// prototype main() { ---------} void function_name(type &parameter_name)
  • 29. Function Call Example #include<iostream.h> int squareVal(int); //prototype call by value function void squareRef(int &); // prototype call by –reference function int main() { int x=2; z=4; cout<< “x=“ << x << “before calling squareVal”; cout << “n” << squareVal(x) << “n”; // call by value cout<< “x=“ << x << “After returning” cout<< “z=“ << z << “before calling squareRef”; squareRef(z); // call by reference cout<< “z=“ << z<< “After returning squareRef” return 0; x=2 before calling squareVal } 4 int squareVal(int a) x=2 after returning { z=4 before calling squareRef return a*=a; // caller’s argument not modified z=16 after returning squareRef } void squarRef(int &cRef) { cRef *= cRef; // caller’s argument modified }
  • 30. Random Number Generator  rand function generates an integer between 0 and RAND-  MAX(~32767) a symbolic constant defined in <stdlib.h> You may use modulus operator (%) to generate numbers within a specifically range with rand. //generate 10 random numbers open-range int x; for( int i=0; i<=10; i++){ x=rand(); cout<<x<<“ “; } ------------------------------------------------------//generate 10 integers between 0……..49 int x; for( int i=0; i<10; i++){ x=rand()%50; cout<<x<<“ “; }
  • 31. Random Number Generator //generate 10 integers between 5…15 int x; for ( int i=1; i<=10; i++){ x= rand()%11 + 5; cout<<x<<“ “; } ------------------------------------ //generate 100 number as simulation of rolling a dice int x; for (int i=1; i<=100; i++){ x= rand%6 + 1; cout<<x<<“ “; }
  • 32. Random Number Generator    the rand( ) function will generate the same set of random numbers each time you run the program . To force NEW set of random numbers with each new run use the randomizing process Randomizing is accomplished with the standard library function srand(unsigned integer); which needs a header file <stdlib.h> Explanation of signed and unsigned integers:  int is stored in at least two-bytes of memory and can have positive & negative values  unsigned int also stored in at least two-bytes of memory but it can have only positive values 0…..65535
  • 33. Randomizing with srand #include<iostream.h> #include<iomanip.h> #include<stdlib.h> int main() { int i; unsigned num; // we will enter a different number each time we run cin>>num; srand(num); for(i=1; i<=5; i++) cout<<setw(10)<< 1+rand()%6; return 0; } Output for Multiple Runs 19 18 3 0 3 6 6 1 1 1 1 1 2 5 2 1 5 5 5 5 4 1 6 3 6 2 4 2 5 3 1 4 4 5 4 Different-set of Random numbers
  • 34. without srand #include<iostream.h> #include<iomanip.h> #include<stdlib.h> int main() { int i; for(i=1; i<=5; i++) cout<<setw(10)<< 1+rand()%6; return 0; } Output for Multiple Runs 5 5 5 5 6 3 3 3 3 5 3 3 3 3 3 5 5 5 5 3 4 4 4 4 5 2 2 2 2 4 Same set of numbers for each run
  • 35. Function Overloading  Function overloading Functions with same name and different parameters  Should perform similar tasks   I.e., function to square ints and function to square floats int square( int x) {return x * x;} float square(float x) { return x * x; }  A call-time c++ complier selects the proper function by examining the number, type and order of the parameters
  • 36. C++ Variables • A variable is a place in memory that has – – – – A name or identifier (e.g. income, taxes, etc.) A data type (e.g. int, double, char, etc.) A size (number of bytes) A scope (the part of the program code that can use it) • Global variables – all functions can see it and using it • Local variables – only the function that declare local variables see and use these variables – A life time (the duration of its existence) • Global variables can live as long as the program is executed • Local variables are lived only when the functions that define these variables are executed 36
  • 37. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } 37
  • 38. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 0 38
  • 39. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 1 0 void main() { f2(); cout << x << endl ; } 39
  • 40. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 4 0 2 void f2() { x += 4; f1(); } 1 void main() { f2(); cout << x << endl ; } 40
  • 41. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 4 3 1 5 4 void f1() { x++; } void f2() { x += 4; f1(); } void main() { f2(); cout << x << endl ; } 41
  • 42. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 5 3 1 5 4 void f1() { x++; } void f2() { x += 4; f1(); } void main() { f2(); cout << x << endl; } 42
  • 43. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 6 1 5 4 void f2() { x += 4; f1(); } void main() { f2(); cout << x << endl; } 43
  • 44. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 7 5 4 void main() { f2(); cout << x << endl; } 44
  • 45. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 8 5 4 void main() { f2(); cout << x << endl; } 45
  • 46. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } 46
  • 47. What is Bad About Using Global Vairables? • Not safe! – If two or more programmers are working together in a program, one of them may change the value stored in the global variable without telling the others who may depend in their calculation on the old stored value! • Against The Principle of Information Hiding! – Exposing the global variables to all functions is against the principle of information hiding since this gives all functions the freedom to change the values stored in the global variables at any time (unsafe!) 47
  • 48. Local Variables • Local variables are declared inside the function body and exist as long as the function is running and destroyed when the function exit • You have to initialize the local variable before using it • If a function defines a local variable and there was a global variable with the same name, the function uses its local variable instead of using the global variable 48
  • 49. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 49
  • 50. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature x 0 Global variables are automatically initialized to 0 void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 50
  • 51. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature x 0 void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 1 void main() { x = 4; fun(); cout << x << endl; } 51
  • 52. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 4 x void fun() x ???? { int x = 10; cout << x << endl; 3 } 2 void main() { x = 4; fun(); cout << x << endl; } 52
  • 53. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 4 x void fun() x 10 { int x = 10; cout << x << endl; 3 } 2 void main() { x = 4; fun(); cout << x << endl; } 53
  • 54. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 4 x void fun() x 10 { int x = 10; cout << x << endl; 4 } 2 void main() { x = 4; fun(); cout << x << endl; } 54
  • 55. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 4 x void fun() x 10 { int x = 10; cout << x << endl; 5 2 } void main() { x = 4; fun(); cout << x << endl; } 55
  • 56. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature x 4 void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 6 void main() { x = 4; fun(); cout << x << endl; } 56
  • 57. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature x 4 void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 7 void main() { x = 4; fun(); cout << x << endl; } 57
  • 58. II. Using Parameters • Function Parameters come in three flavors: – Value parameters – which copy the values of the function arguments – Reference parameters – which refer to the function arguments by other local names and have the ability to change the values of the referenced arguments – Constant reference parameters – similar to the reference parameters but cannot 58 change the values of the referenced
  • 59. Value Parameters • This is what we use to declare in the function signature or function header, e.g. int max (int x, int y); – Here, parameters x and y are value parameters – When you call the max function as max(4, 7), the values 4 and 7 are copied to x and y respectively – When you call the max function as max (a, b), where a=40 and b=10, the values 40 and 10 are copied to x and y respectively – When you call the max function as max( a+b, b/2), the values 50 and 5 are copies to x and y respectively • Once the value parameters accepted copies of the corresponding arguments data, they act as local variables! 59
  • 60. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 1 0 void main() { x = 4; fun(x/2+1); cout << x << endl; } 60
  • 61. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 3 2 4 void fun(int x ) { cout << x << endl; x=x+5; } void main() { 3 x = 4; fun(x/2+1); cout << x << endl; } 61
  • 62. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 4 2 4 void fun(int x 3 ) 8 { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } 62
  • 63. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 5 2 4 void fun(int x 3 ) 8 { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } 63
  • 64. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 6 4 void main() { x = 4; fun(x/2+1); cout << x << endl; } 64
  • 65. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 7 4 void main() { x = 4; fun(x/2+1); cout << x << endl; } 65
  • 66. Reference Parameters • As we saw in the last example, any changes in the value parameters don’t affect the original function arguments • Sometimes, we want to change the values of the original function arguments or return with more than one value from the function, in this case we use reference parameters – A reference parameter is just another name to the original argument variable – We define a reference parameter by adding the & in front of the parameter name, e.g. double update (double & x); 66
  • 67. Example of Reference Parameters #include <iostream.h> void fun(int &y) { cout << y << endl; y=y+5; } void main() { int x = 4; // Local variable fun(x); cout << x << endl; } 1 void main() { 4 ? int x = 4; fun(x); cout << x << endl; } x 67
  • 68. Example of Reference Parameters #include <iostream.h> void fun(int &y) { cout << y << endl; y=y+5; } void main() { int x = 4; // Local variable fun(x); cout << x << endl; } 3 2 void fun( int & y { cout<<y<<endl; y=y+5; } void main() { 4 ? int x = 4; fun(x); cout << x << endl; } ) x 68
  • 69. Example of Reference Parameters #include <iostream.h> void fun(int &y) { cout << y << endl; y=y+5; } void main() { int x = 4; // Local variable fun(x); cout << x << endl; } 4 2 void fun( int & y { cout<<y<<endl; y=y+5; 9 } void main() { 4 ? int x = 4; fun(x); cout << x << endl; } ) x 69
  • 70. Example of Reference Parameters #include <iostream.h> void fun(int &y) { cout << y << endl; y=y+5; } void main() { int x = 4; // Local variable fun(x); cout << x << endl; } 5 2 void fun( int & y { cout<<y<<endl; y=y+5; } void main() { 9 ? int x = 4; fun(x); cout << x << endl; } ) x 70
  • 71. Example of Reference Parameters #include <iostream.h> void fun(int &y) { cout << y << endl; y=y+5; } void main() { int x = 4; // Local variable fun(x); cout << x << endl; } 6 void main() { 9 ? int x = 4; fun(x); cout << x << endl; } x 71
  • 72. Example of Reference Parameters #include <iostream.h> void fun(int &y) { cout << y << endl; y=y+5; } void main() { int x = 4; // Local variable fun(x); cout << x << endl; } 7 void main() { 9 ? int x = 4; fun(x); cout << x << endl; } x 72
  • 73. Constant Reference Parameters • Constant reference parameters are used under the following two conditions: – The passed data are so big and you want to save time and computer memory – The passed data will not be changed or updated in the function body • For example void report (const string & prompt); • The only valid arguments accepted by reference parameters and constant reference parameters are variable names – It is a syntax error to pass constant values or expressions to the (const) reference parameters 73
  • 74. Header Files • Header files – Contain function prototypes for library functions – <stdlib.h> , <math.h> , etc – Load with #include <filename> #include <math.h> • Custom header files – Create file with functions – Save as filename.h – Load in other files with #include
  • 75. Scope Rules • File scope – Identifier defined outside function, known in all functions – Used for global variables, function definitions, function prototypes • Function scope – Can only be referenced inside a function body – Used only for labels (start:, case: , etc.)
  • 76. Scope Rules • Block scope – Identifier declared inside a block • Block scope begins at declaration, ends at right brace – Used for variables, function parameters (local variables of function) – Outer blocks "hidden" from inner blocks if there is a variable with the same name in the inner block • Function prototype scope