0% found this document useful (0 votes)
23 views21 pages

TL09.2 IPL Functions 1

The document outlines the concepts of functions in programming, specifically focusing on their structure, modular design, and the roles of local and global variables. It explains the importance of functions in breaking down complex problems into manageable modules, and details the syntax for function declaration and definition in C/C++. Additionally, it covers the main function, transfer of control flow, function arguments, and variable scope within the context of programming.
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)
23 views21 pages

TL09.2 IPL Functions 1

The document outlines the concepts of functions in programming, specifically focusing on their structure, modular design, and the roles of local and global variables. It explains the importance of functions in breaking down complex problems into manageable modules, and details the syntax for function declaration and definition in C/C++. Additionally, it covers the main function, transfer of control flow, function arguments, and variable scope within the context of programming.
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/ 21

Functions

Course Code: CSC1102 &1103 Course Title: Introduction to Programming

Dept. of Computer Science


Faculty of Science and Technology

Lecturer No: 9.2 Week No: 9 Semester: Spring 2024-2025


Course Mashiour Rahman, Associate Professor,
Instructor: [email protected]
Lectures 8: Outline
 Functions as Modular design
 Structure of a function
 Declaration & Definition
 The main() function
 Transfer of control flow using function
 Arguments
 Local Variables – scope, autometic, static, global
 Returning Function Results
Modular Design
 Most effective strategy when designing and writing a complex program is to break
down the program into several smaller modules i.e. a small self-contained section of
an algorithm.
 In modular design, each major program step and/or operation is implemented as an
independent program module or subprogram. These modules are then combined to
form a complete program.
 Modular design is much easier to develop, debug, test, and update.
 Modules are reusable since a block of code can be reused in many different contexts
without repeating parts of the program text.
 Modules hide details of operation from parts of the program that don't need to know
about them, thus clarifying the whole, and easing the pain of making changes.

 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

Function in programming has various additional features.


Function – Declaration
rType Function_Name(pType1 v1, pType2 v2, … , pTypeN vN);
Just like a variable declaration a function must also be declared along with its
components – return type, function name, and parameter list.
This is also known as function prototype.
A function declaration says nothing about what the function does exactly (no function
body).

int x; int f(int x);


A location (&x) to store an integer A location (&f) to store the address of the
variable is created. body of the function.
When x is called/invoked, goes to the When f(x) is called/invoked, goes to the
location of the variable x and put/get location of the function body and get value as
value to/from the location directly. return after executing the statements.
Example: x=5; y=x; Example: y=f(5);
Function – Definition
rType Function_Name(pType1 v1, pType2 v2, … , pTypeN vN)
{
// statements;
return vR; // only if rType is not void
}
 The compiler must know the function declaration to enable it to properly interpret the
invocations of the function.
 That information is provided by the function body, which is a separate part of the code,
enclosed in brackets.
 The definition is pointed to by the address &Function_Name from the declaration.
 A function declaration enriched with a function body forms the function definition.
 A function definition can act as both declaration and definition depending on the position of
the caller function.
 The function definition must come before the caller function.
 If a function f1() calls function f2() and the definition of f2() is before definition of
f1(), then declaration for f2() is not required.
Function – Declaration and
Definition
#include <iostream> #include <iostream>
using namespace std; using namespace std;
//declaration //declaration-definition
void printMessage(void); void printMessage(void)
{
int main (void) cout << "Function\n";
{ //calling function }
printMessage();
printMessage(); int main (void)
return 0; { //caller function
} printMessage();
printMessage();
//definition return 0;
void printMessage(void) }
{
cout << "Function\n";  A function definition can act as both declaration and
} definition depending on the position of the caller
function.
 A calling function is the one that  The function definition must come before the caller
calls/invokes a function within function.
its body.  If a function f1() calls function f2() and the
 Here main() is the caller definition of f2() is before definition of f1(), then
function. declaration for f2() is not required.
The main Function
 Every C/C++ program code (*.cpp) is compiled to produce an executable file (*.exe).
 When you execute a C/C++ executable file, the operating system calls the main
function of your program. Program execution begins with the first statement in main.
 Any C function can call any of the other
fun3 functions in a program including itself and be
fun1
called by any other function. But there must be
main fun4 fun6
at least one function in your program that must
fun2 be called main function as it indicates the
fun5
starting point of your program execution.

 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);

// called function cin >> u >> v; //input 83 240


int gcd(int u,int v) cout<<"GCD("<<
cout<< u <<endl;
gcd(u, v) <<","<< v <<"):
{… ";
return u; } gcd(u, v); OUTPUT:
int r= gcd( u,
v*9); return 0; GCD(150, 35): 5
} GCD(1026, 405): 27
int main (void){… …} GCD(83, 240): 1
Global variables
 A global variable declaration is made outside of any function. It does not belong to
any particular function.
 The lifetime of a global variable is from it’s declaration to the end of the program.
 Any function in the program can then access and/or change the value of the global
variable.
 The primary use of global variables is in programs in which many functions must
access the value of the same variable. Rather than having to pass the value of the
variable to each individual function as an argument, the function can explicitly
reference the variable instead.
 There is a drawback with this approach: Because the function explicitly references a
particular global variable, the generality of the function is somewhat reduced !
 Global variables do have default initial values: zero
Example: global variables
#include<iostream> OUTPUT: int main(void) {
using namespace std; int e;
9 Top=0;
int Stack[5], Top, N=5;
3 Push(1);
bool Full(){ return (Top == N);} Push(2);
bool Empty(){return (Top == 0);} Push(3);
Push(9);
void Push(int e){ if(Pop(&e)) cout<< e
if(Full()) cout<<"Error: Full\ <<endl;
n"; if(Pop(&e)) cout<< e
else Stack[Top++] = e; <<endl;
} Push(4);
Push(8);
int Pop(int *e){ Push(16);
if(Empty()){ Push(32);
Top 4
cout<<"Error: Empty\n"; if(Pop(&e)) cout<< e
return 0; Top 3 9
8 <<endl;
} if(Pop(&e)) cout<< e
*e = Stack[--Top];
Top 2 4
3
<<endl;
return 1; Pop Top 1 2 if(Pop(&e)) cout<< e
} <<endl;
e= Top 0 1
if(Pop(&e)) cout<< e
e= 4
1
9
3
2
8 e 3
*e= 9 N=5 Stack[5 <<endl;
= ] if(Pop(&e)) cout<< e
Pus mai Global variables <<endl;
Example: global variables
#include<iostream> OUTPUT: int main(void) {
using namespace std; int e;
9 Top=0;
int Stack[5], Top, N=5;
3 Push(1);
bool Full(){ return (Top == N);}Error: Full Push(2);
16 Push(3);
bool Empty(){return (Top == 0);}8
Push(9);
void Push(int e){ 4 if(Pop(&e)) cout<< e
2 <<endl;
if(Full()) cout<<"Error: Full\ 1
n"; if(Pop(&e)) cout<< e
Error: <<endl;
else Stack[Top++] = e; Empty
} Push(4);
Push(8);
int Pop(int *e){ Top 5 Push(16);
if(Empty()){ Push(32);
Top 4 16
cout<<"Error: Empty\n"; if(Pop(&e)) cout<< e
return 0; Top 3 8 <<endl;
} if(Pop(&e)) cout<< e
*e = Stack[--Top];
Top 2 4
<<endl;
return 1; Pop Top 1 2 if(Pop(&e)) cout<< e
} e= <<endl;
Top 0 1
if(Pop(&e)) cout<< e
e= 16
32 *e=
e 16
1
3
2
4
8 N=5 Stack[5 <<endl;
= ] if(Pop(&e)) cout<< e
Pus mai Global variables <<endl;
Static local variables
 Placing the key word static in front of a variable declaration makes it a static local
variable within the function.
 The word static mean "something that has no movement".
 A static local variable –
 Is created only once in the very first function call and doesn’t get destroyed when the function
exits.
 Have default initial values of zero, unlike automatic variables, which have no default initial
value.
 Is initialized only once at the first function call and not each time that the function is called.
Even if a specific statement like static int x = 5; exists inside the function, the
statement will only be executed in the first function call. The initial value specified for a static
variable must be a simple constant or constant expression.
 Cannot be accessed from any other function.
 The value of a static variable upon leaving a function is the same value that variable will
have the next time the function is called.
Example: Static local variables
// static and automatic local variables
#include<iostream>
using namespace std; Main Memory
void auto_static (void){ 1
0
i = 3
2
int autoVar = 1; autoVar = 2
1
static int staticVar = 1;
1
2
staticVar 4
3
cout <<"automatic = "<< autoVar <<" "
=
<<", static = "<< staticVar
<<endl;
++autoVar;
++staticVar;
} OUTPUT:
int main (void){
automatic = 1 , static = 1
int i;
automatic = 1 , static = 2
for ( i = 0; i < 3; ++i ) automatic = 1 , static = 3
auto_static ();
return 0;
}

You might also like