TL09.2 IPL Functions 1
TL09.2 IPL Functions 1
The programming languages fully supports modular design through the concept of
functions.
What is a function?
A function is a self-contained unit of program code designed to accomplish a particular
task.
Functions enable developers to divide a problem (and also a code) into smaller parts
The concept has some equivalent in all high-level programming languages: functions,
subroutines, and procedures
Function is defined in terms of the information that goes in (its input) and the value or
action it produces (its output).
Some functions find a value for a program to use. Example: strlen(s1) returns
the length of the string s1 to the program.
Some functions cause an action to take place. Example: strcpy(s1,s2) causes
to copy all the content of s2 into s1.
A function can both produce actions and provide values.
In general, we can divide functions into two groups:
Library functions - strlen(s1), strcpy(s1,s2), etc.
User-defined functions – we are learning now
The Structure of a C Function
Function header:
Specifies the function name, type of value that the function returns, list of parameters.
The arguments/parameters (or formal parameters/variables vi), each with their respective data
type (pTypei) separated by coma (,). More about it later.
Function Body :
The function body specifies the tasks, statements, instructions that the function will carry out
enclosed within the brackets {}.
The function exits with the statement return vR; only if rType is not void, where
variable/expression vR is generally of data type rType. If the type of vR does not match with
rType, value of vR is automatically converted to rType before it is returned.
The value of variable/expression vR is returned to the calling function. If rType does not match
with the type where vR is returned in the calling function, the returned value is automatically
converted to the type as per the calling function after it is returned.
if rType is void it may contain simply return; or nothing.
The return statement may contain anywhere in the body.
data type of the returned As per rule of v1,v2,…,vN are the variables and pType1,pType2,…,pTypeN
value. void if no return. the identifier are their respective data types. () or (void) if no
parameter.
rType Function_Name(pType1 v1, pType2 v2, … , pTypeN
{ vN)
/* body of the function – statements/instructions
*/
return vR; // only if rType is not void
Functions – Arithmetic vs
Programming Any programming function,
Any arithmetic function,
Any arithmetic function, Any programming function,
f(x) = x22 + 2 where x N. int fp(int x){
f(2) = 222 + 2 = 6 int i = x2 + 2;
f(3)
f(3) =
= 322
3 +
+ 2
2 = 11
= 11 return i;
f(4)
f(4) =
= 422
4 +
+ 2
2 = 18
= 18 }
is the
f is
f the function
function name
name fp is
fp is the
the function
function name.
name.
(x) isisthe
(x) theinput
inputparameter
parameter (there
(there (int
(int x) x) isis the
the input parameter with
input parameter with data
data type
type
can be
can be multiple
multiple parameter)
parameter) (there
(there can
can be
be multiple
multiple parameter)
parameter)
x 2 +2 is the operation to perform int is the
the instruction(s)
instruction(s) to
to execute
execute
int i i == xx2 ++ 2;
2 2
x +2 is the operation to perform 2; is
given after
given after = operator.
= operator. within
within the
the scope
scope {
{ } } of
of curly
curly bracket.
bracket.
After operation with a specific value return i; is the instruction to set the result for
After operation with a specific value return i; is the instruction to set the result for
of x the result of function f(x) is fp(x) for a specific value of x whose data type is
of
set.x the result of function f(x) is fp(x) for a specific value of x whose data type is
indicated by int before function name fp.
set. f(2) = 6 indicated by int before function name fp.
int a = fp(2); //a = 6
f(2)
f(3) = = 611 int a = fp(2); //a = 6
int b = fp(3); //b = 11
f(3)
f(4) = = 11
18 int b = fp(3); //b = 11
int c = fp(4); //c = 18
f(4) = 18 int c = fp(4); //c = 18
The main function returns an integer that gives the correctness of the program
execution. A return value of 0 means executed correctly, while a non-zero value is an
error code of some kind.
If the arguments/parameters of main function is empty, it is shown as () or (void).
If there are arguments in main, that must be passed externally by the user as main
has no calling function. That makes it different and unique from other functions’
arguments.
The main Function - arguments
The (command line) arguments of main function is
/* test1.cpp which produces
called by the Operating System. The user must type in test1.exe after compilation */
the executable file name followed by the arguments in
#include<iostream>
the command line. The syntax –
int main(int argc, char *argv[]) using namespace std;
The value in argc (argument count) is the number int main(int argc, char *argv[])
{
of command line arguments that you have passed
// type in command prompt
or typed in the console.
The argv (argument vector) parameter is an array // > test1.exe C++ program
of pointers to the arguments // argc = Total count of
This type is useful for programs that need to handle arguments
external input, such as filenames, options, or // Here 3 including file name
parameters passed at the time of execution.
cout << argc << endl;
COMMAND PROMPT: // Showing each argument
for (int i = 0; i < argc; i++)
D:\CodeBlocks\MinGW\bin>test1.exe C++ program {
3
test1.exe cout << argv[i] << endl;
C++ }
program return 0;
Transfer of control flow
void fun3(void){
void fun1(void){ cout << "fun3\
cout << "fun1\ n"; void fun6(void){
n"; } cout << "fun6\
fun3(); n";
int main(void){ fun4(); void fun4(void){ }
cout << "main\ } cout << "fun4\
n"; n"; OUTPUT:
fun1(); fun6(); main
fun2(); } fun1
fun4(); fun3
return 0; void fun5(void){ fun4
} void fun2(void){ cout << "fun5\ fun6
cout << "fun2\ n"; fun2
n"; } fun5
fun5();
} fun4
fun6
• When a function call is executed, program execution is transferred directly to the location
of the function body indicated by the function name.
• After the called routine/function is finished (as signaled by the closing brace) the program
returns to the calling routine/function, where program execution continues at the point
where the function call was executed.
Function Arguments
Arguments (Parameters): a kind of input for the function blackbox
In the function definition: formal arguments (formal parameters)
A name that is used inside the function body to refer to its arguments (here x, y, z ).
void printMessage(int x, int y, int z){
cout << x << y << z;
}
In the function call: actual arguments (actual parameters)
The actual arguments are values (constant, a variable, or an even more elaborate
expression) that are assigned to the corresponding formal parameters.
The actual argument is evaluated, and its value is copied to the corresponding formal
// called function
parameter for the function. void printMessage(int x,int y,int
void Fun (void){ z){…}
int a=2, b=4, c=6; // calling function
printMessage(c, a*b+1, 8);void Fun (void){…
} printMessage( c, a*b+1,
8);}
Because the called function works with data copied from the calling function, the original
data in the calling function is protected from whatever manipulations the called function
Scope of variables
Lifetime of variables: Period of time when memory location is allocated to a declared
variable up to the deallocated of that memory
Scope of variables:
Region of program text where variable/location/value is accessible.
Any variable declared inside within the curly bracket {} is only recognized/active from its’
declaration point up to the end of curly bracket. At which point the variable is destroyed.
Exception: declared variable in the initialization part of a for loop has scope up to the end of
that loop.
Local variables: any variable that is declared inside (within the curly bracket {}) a
function and with in its parameter/argument list is a local variable to that function.
Local variables are automatically created each time the function is called and destroyed when
the function returns. Also known as automatic local variables.
The local variable can only be accessed by the function in which the variable is defined. No
other function can access those variables and their values.
Local variables have no default initial value.
Scope of variables, Prologues &Epilogues, and
function stack Program Segments: Conceptually,
#include<iostream>
using namespace std; every program allocates three segments in
the main memory during execution –
void f1 (int n){
• Code Segment: where the executable code is stored.
int x = n+6;
• Data Segment: where the declared data is allocated.
cout<< x << endl;
• Stack Segment: dynamic memory allocation and function
}
call information
int f2(float n){ Prologues and Epilogues:
n /= 2; • A prologue is the part of the code that implicitly executes
cout << n << endl; before the function responsible for transferring
} parameters from the invoker's code and for storing them
int f3(void){ in a special transient area called a "stack".
int n=10; • The epilogue is implicitly executed just after the function's
f2(n); code responsible for transferring the result of the function
cout << n << endl; and for clearing the stack of the values placed there by the
} prologue.
int main(void){
int n=25; Main Memory OUTPUT:
f1(3); n=25 9
f1(n); 31
f2(n); n=3
n=12.5
n=25.0
n=10
n=25
12.50
f3(); 0 f3.n=10
n=10.0
n=5.00
x=31
x=9 5.00
cout << n << endl; 0 main.n=25 10
return 0;
} Stack 25
Example: Greatest Common Divisor (GCD)
#include<iostream> int main (void){
using namespace std; int u, v;
int gcd (int u, int v){
void
int temp; cout<<"GCD(150, 35): ";
while ( v != 0 ){ gcd(150,
cout<< 35);
gcd(150, 35)
temp = u % v; <<endl;
u = v; u = 1026, v=45;
v = temp; cout<<"GCD("<< u <<","<< v*9 <<"):
} ";int r = gcd(u, v*9);
cout <<u
return u; << endl; cout<<
gcd(u, rv*9); // (1026, 405)
} <<endl;//(1026,405);