SlideShare a Scribd company logo
1 of 6
Download to read offline
Functions Intro to Programming
MUHAMMAD HAMMAD WASEEM 1
Functions
Using functions we can structure our programs in a more modular way, accessing all the potential
that structured programming can offer to us in C/C++.
A function is a group of statements that is executed when it is called from some point of the
program. The following is the syntax of function:
type name (parameter1, parameter2, ...) { statements }
where:
ļ‚· type is the data type specifier of the data returned by the function.
ļ‚· name is the identifier by which it will be possible to call the function.
ļ‚· parameters (as many as needed): Each parameter consists of a data type specifier followed by
an identifier, like any regular variable declaration (for example: int x) and which acts within
the function as a regular local variable. They allow to pass arguments to the function when it is
called. The different parameters are separated by commas.
ļ‚· statements is the function's body. It is a block of statements surrounded by braces { }.
Here you have the first function example:
// function example
#include <stdio.h>
#include <conio.h>
int addition (int a, int b)
{
int r;
r=a+b;
return (r);
}
void main ()
{
int z;
z = addition (5,3);
printf("The result is %d", z);
getch();
}
In order to examine this code, first of all remember something said at the beginning of this
course that a C/C++ program always begins its execution by the main function. So we will begin there.
We can see how the main function begins by declaring the variable z of type int. Right after
that, we see a call to a function called addition. Paying attention we will be able to see the similarity
between the structure of the call to the function and the declaration of the function itself some code
Functions Intro to Programming
MUHAMMAD HAMMAD WASEEM 2
lines above:
The parameters and arguments have a clear correspondence. Within the main function we
called to addition passing two values: 5 and 3, that correspond to the int a and int b parameters
declared for function addition.
At the point at which the function is called from within main, the control is lost by main and
passed to function addition. The value of both arguments passed in the call (5 and 3) are copied to the
local variables int a and int b within the function.
Function addition declares another local variable (int r), and by means of the expression r=a+b,
it assigns to r the result of a plus b. Because the actual parameters passed for a and b are 5 and 3
respectively, the result is 8.
The following line of code:
return (r);
finalizes function addition, and returns the control back to the function that called it in the first place
(in this case, main). At this moment the program follows its regular course from the same point at
which it was interrupted by the call to addition. But additionally, because the return statement in
function addition specified a value: the content of variable r (return (r);), which at that moment had a
value of 8. This value becomes the value of evaluating the function call.
So being the value returned by a function the value given to the function call itself when it is evaluated,
the variable z will be set to the value returned by addition (5, 3), that is 8. To explain it another way,
you can imagine that the call to a function (addition (5,3)) is literally replaced by the value it returns
(8).
The following line of code in main is:
printf("The result is %d", z);
Important points about Functions
āˆ’ Any C program contains at least one function.
āˆ’ If a program contains only one function, it must be main( ).
āˆ’ If a C program contains more than one function, then one (and only one) of these functions must
be main( ), because program execution always begins with main( ).
āˆ’ There is no limit on the number of functions that might be present in a C program.
āˆ’ Each function in a program is called in the sequence specified by the function calls in main( ).
Functions Intro to Programming
MUHAMMAD HAMMAD WASEEM 3
āˆ’ After each function has done its thing, control returns to main( ).When main( ) runs out of function
calls, the program ends.
Well, letā€™s illustrate with an example.
main( )
{
printf ( "nI am in main" ) ;
italy( ) ;
printf ( "nI am finally back in main" ) ;
}
italy( )
{
printf ( "nI am in italy" ) ;
brazil( ) ;
printf ( "nI am back in italy" ) ;
}
brazil( )
{
printf ( "nI am in brazil" ) ;
argentina( ) ;
}
argentina( )
{
printf ( "nI am in argentina" ) ;
}
And the output would look like...
I am in main
I am in italy
I am in brazil
I am in argentina
I am back in italy
I am finally back in main
Let us now summarize what we have learnt so far.
a) C program is a collection of one or more functions.
b) A function gets called when the function name is followed by a semicolon. For example,
main( )
{
argentina( ) ;
}
c) A function is defined when function name is followed by a pair of braces in which one or more
statements may be present. For example,
argentina( )
Functions Intro to Programming
MUHAMMAD HAMMAD WASEEM 4
{
statement 1 ;
statement 2 ;
statement 3 ;
}
d) Any function can be called from any other function. Even main( ) can be called from other
functions. For example,
main( )
{
message( ) ;
}
message( )
{
printf ( "nCan't imagine life without C" ) ;
main( ) ;
}
e) A function can be called any number of times. For example,
main( )
{
message( ) ;
message( ) ;
}
message( )
{
printf ( "nJewel Thief!!" ) ;
}
f) The order in which the functions are defined in a program and the order in which they get called
need not necessarily be same. For example,
main( )
{
message1( ) ;
message2( ) ;
}
message2( )
{
printf ( "nBut the butter was bitter" ) ;
}
message1( )
{
printf ( "nMary bought some butter" ) ;
}
Functions Intro to Programming
MUHAMMAD HAMMAD WASEEM 5
g) A function can call itself. Such a process is called ā€˜recursionā€™. We would discuss this aspect of C
functions later in this chapter.
Types of Functions:
There are basically two types of functions:
1. Library functions Ex. printf( ), scanf( ) etc.
2. User-defined functions Ex. argentina( ), brazil( ) etc.
As the name suggests, library functions are nothing but commonly required functions grouped together
and stored in what is called a Library. This library of functions is present on the disk and is written for us
by people who write compilers for us. Almost always a compiler comes with a library of standard
functions. The procedure of calling both types of functions is exactly same.
Why Use Functions
Why write separate functions at all? Why not squeeze the entire logic into one function, main( )? Two
reasons:
1. Writing functions avoids rewriting the same code over and over.
ļƒ˜ Suppose you have a section of code in your program that calculates area of a triangle. If later in the
program you want to calculate the area of a different triangle, you wonā€™t like it if you are required to
write the same instructions all over again. Instead, you would prefer to jump to a ā€˜section of codeā€™
that calculates area and then jump back to the place from where you left off. This section of code is
nothing but a function.
2. Using functions it becomes easier to write programs and keep track of what they are doing.
ļƒ˜ If the operation of a program can be divided into separate activities, and each activity placed in a
different function, then each could be written and checked more or less independently. Separating
the code into modular functions also makes the program easier to design and understand.
Scope Rule of Functions
Look at the following program
main( )
{
int i = 20 ;
display ( i ) ;
}
display ( int j )
{
int k = 35 ;
printf ( "n%d", j ) ;
printf ( "n%d", k ) ;
}
In this program is it necessary to pass the value of the variable i to the function display( )? Will it not
become automatically available to the function display( )? No. Because by default the scope of a
variable is local to the function in which it is defined. The presence of i is known only to the function
main( ) and not to any other function. Similarly, the variable k is local to the function display( ) and
hence it is not available to main( ). In general we can say that the scope of a variable is local to the
function in which it is defined.
Functions Intro to Programming
MUHAMMAD HAMMAD WASEEM 6
Call by Value and Call by Reference
By now we are well familiar with how to call functions. But, if you observe carefully, whenever
we called a function and passed something to it we have always passed the ā€˜valuesā€™ of variables to the
called function. Such function calls are called ā€˜calls by valueā€™. By this what we mean is, on calling a
function we are passing values of variables to it. The examples of call by value are shown below:
sum = calsum ( a, b, c ) ;
f = factr ( a ) ;
We have also learnt that variables are stored somewhere in memory. So instead of passing the
value of a variable, can we not pass the location number (also called address) of the variable to a
function? If we were able to do so it would become a ā€˜call by referenceā€™. What purpose a ā€˜call by
referenceā€™ serves we would find out a little later. First we must equip ourselves with knowledge of how
to make a ā€˜call by referenceā€™. This feature of C functions needs at least an elementary knowledge of a
concept called ā€˜pointersā€™. So let us first acquire the basics of pointers after which we would take up this
topic once again

More Related Content

What's hot

C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2Vikram Nandini
Ā 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1Vikram Nandini
Ā 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C v_jk
Ā 
Basics of c++
Basics of c++ Basics of c++
Basics of c++ Gunjan Mathur
Ā 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c languagetanmaymodi4
Ā 
Ch3 repetition
Ch3 repetitionCh3 repetition
Ch3 repetitionHattori Sidek
Ā 
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)Mansi Tyagi
Ā 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c languagetanmaymodi4
Ā 
Recursion in c
Recursion in cRecursion in c
Recursion in cSaket Pathak
Ā 
Overview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiOverview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiSowmya Jyothi
Ā 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CSowmya Jyothi
Ā 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and typesimtiazalijoono
Ā 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
Ā 
Unit iv functions
Unit  iv functionsUnit  iv functions
Unit iv functionsindra Kishor
Ā 

What's hot (20)

C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
Ā 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
Ā 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
Ā 
Basics of c++
Basics of c++ Basics of c++
Basics of c++
Ā 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
Ā 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
Ā 
Ch3 repetition
Ch3 repetitionCh3 repetition
Ch3 repetition
Ā 
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
Ā 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
Ā 
Lecture 14 - Scope Rules
Lecture 14 - Scope RulesLecture 14 - Scope Rules
Lecture 14 - Scope Rules
Ā 
Recursion in c
Recursion in cRecursion in c
Recursion in c
Ā 
Overview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiOverview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya Jyothi
Ā 
Lecture 13 - Storage Classes
Lecture 13 - Storage ClassesLecture 13 - Storage Classes
Lecture 13 - Storage Classes
Ā 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in C
Ā 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
Ā 
Functions in c language
Functions in c language Functions in c language
Functions in c language
Ā 
Unit iv functions
Unit  iv functionsUnit  iv functions
Unit iv functions
Ā 
Scope of variables
Scope of variablesScope of variables
Scope of variables
Ā 
Pointers in C language
Pointers  in  C languagePointers  in  C language
Pointers in C language
Ā 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
Ā 

Similar to Functions Intro: Modular Programming with C/C++ Functions

Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptxMehul Desai
Ā 
Functionincprogram
FunctionincprogramFunctionincprogram
FunctionincprogramSampath Kumar
Ā 
Amit user defined functions xi (2)
Amit  user defined functions xi (2)Amit  user defined functions xi (2)
Amit user defined functions xi (2)Arpit Meena
Ā 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxvekariyakashyap
Ā 
unit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfunit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfJAVVAJI VENKATA RAO
Ā 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxSangeetaBorde3
Ā 
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdfUSER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdfSowmyaJyothi3
Ā 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptxRhishav Poudyal
Ā 
c.p function
c.p functionc.p function
c.p functiongiri5624
Ā 
Functions
FunctionsFunctions
Functionszeeshan841
Ā 
Basic information of function in cpu
Basic information of function in cpuBasic information of function in cpu
Basic information of function in cpuDhaval Jalalpara
Ā 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxKhurramKhan173
Ā 
Functions assignment
Functions assignmentFunctions assignment
Functions assignmentAhmad Kamal
Ā 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C ProgrammingShuvongkor Barman
Ā 
C programming language working with functions 1
C programming language working with functions 1C programming language working with functions 1
C programming language working with functions 1Jeevan Raj
Ā 

Similar to Functions Intro: Modular Programming with C/C++ Functions (20)

Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
Ā 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
Ā 
Amit user defined functions xi (2)
Amit  user defined functions xi (2)Amit  user defined functions xi (2)
Amit user defined functions xi (2)
Ā 
Function
FunctionFunction
Function
Ā 
Functions
Functions Functions
Functions
Ā 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Ā 
unit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfunit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdf
Ā 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
Ā 
4. function
4. function4. function
4. function
Ā 
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdfUSER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
Ā 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
Ā 
C functions list
C functions listC functions list
C functions list
Ā 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
Ā 
c.p function
c.p functionc.p function
c.p function
Ā 
Functions
FunctionsFunctions
Functions
Ā 
Basic information of function in cpu
Basic information of function in cpuBasic information of function in cpu
Basic information of function in cpu
Ā 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
Ā 
Functions assignment
Functions assignmentFunctions assignment
Functions assignment
Ā 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
Ā 
C programming language working with functions 1
C programming language working with functions 1C programming language working with functions 1
C programming language working with functions 1
Ā 

More from Muhammad Hammad Waseem

[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++Muhammad Hammad Waseem
Ā 
[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++Muhammad Hammad Waseem
Ā 
[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)Muhammad Hammad Waseem
Ā 
[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++Muhammad Hammad Waseem
Ā 
[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++Muhammad Hammad Waseem
Ā 
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of ProgrammingMuhammad Hammad Waseem
Ā 
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming LanguagesMuhammad Hammad Waseem
Ā 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member FunctionsMuhammad Hammad Waseem
Ā 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data MemberMuhammad Hammad Waseem
Ā 
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnTypeMuhammad Hammad Waseem
Ā 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its TypesMuhammad Hammad Waseem
Ā 
[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their AccessingMuhammad Hammad Waseem
Ā 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)Muhammad Hammad Waseem
Ā 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access SpecifiersMuhammad Hammad Waseem
Ā 
[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and ObjectsMuhammad Hammad Waseem
Ā 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOPMuhammad Hammad Waseem
Ā 
[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming Paradigms[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming ParadigmsMuhammad Hammad Waseem
Ā 
[OOP - Lec 02] Why do we need OOP
[OOP - Lec 02] Why do we need OOP[OOP - Lec 02] Why do we need OOP
[OOP - Lec 02] Why do we need OOPMuhammad Hammad Waseem
Ā 

More from Muhammad Hammad Waseem (20)

[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
Ā 
[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++
Ā 
[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)
Ā 
[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes
Ā 
[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++
Ā 
[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++
Ā 
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
Ā 
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
Ā 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
Ā 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
Ā 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member
Ā 
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
Ā 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
Ā 
[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing
Ā 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)
Ā 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
Ā 
[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects
Ā 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP
Ā 
[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming Paradigms[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming Paradigms
Ā 
[OOP - Lec 02] Why do we need OOP
[OOP - Lec 02] Why do we need OOP[OOP - Lec 02] Why do we need OOP
[OOP - Lec 02] Why do we need OOP
Ā 

Recently uploaded

Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
Ā 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
Ā 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
Ā 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
Ā 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
Ā 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
Ā 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
Ā 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
Ā 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
Ā 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
Ā 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
Ā 
18-04-UA_REPORT_MEDIALITERAŠ”Y_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAŠ”Y_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAŠ”Y_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAŠ”Y_INDEX-DM_23-1-final-eng.pdfssuser54595a
Ā 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
Ā 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
Ā 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
Ā 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
Ā 

Recently uploaded (20)

Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”
Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”
Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”
Ā 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
Ā 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
Ā 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
Ā 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
Ā 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Ā 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
Ā 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
Ā 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
Ā 
Model Call Girl in Bikash Puri Delhi reach out to us at šŸ”9953056974šŸ”
Model Call Girl in Bikash Puri  Delhi reach out to us at šŸ”9953056974šŸ”Model Call Girl in Bikash Puri  Delhi reach out to us at šŸ”9953056974šŸ”
Model Call Girl in Bikash Puri Delhi reach out to us at šŸ”9953056974šŸ”
Ā 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Ā 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
Ā 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
Ā 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
Ā 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
Ā 
18-04-UA_REPORT_MEDIALITERAŠ”Y_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAŠ”Y_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAŠ”Y_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAŠ”Y_INDEX-DM_23-1-final-eng.pdf
Ā 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
Ā 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
Ā 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
Ā 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
Ā 

Functions Intro: Modular Programming with C/C++ Functions

  • 1. Functions Intro to Programming MUHAMMAD HAMMAD WASEEM 1 Functions Using functions we can structure our programs in a more modular way, accessing all the potential that structured programming can offer to us in C/C++. A function is a group of statements that is executed when it is called from some point of the program. The following is the syntax of function: type name (parameter1, parameter2, ...) { statements } where: ļ‚· type is the data type specifier of the data returned by the function. ļ‚· name is the identifier by which it will be possible to call the function. ļ‚· parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas. ļ‚· statements is the function's body. It is a block of statements surrounded by braces { }. Here you have the first function example: // function example #include <stdio.h> #include <conio.h> int addition (int a, int b) { int r; r=a+b; return (r); } void main () { int z; z = addition (5,3); printf("The result is %d", z); getch(); } In order to examine this code, first of all remember something said at the beginning of this course that a C/C++ program always begins its execution by the main function. So we will begin there. We can see how the main function begins by declaring the variable z of type int. Right after that, we see a call to a function called addition. Paying attention we will be able to see the similarity between the structure of the call to the function and the declaration of the function itself some code
  • 2. Functions Intro to Programming MUHAMMAD HAMMAD WASEEM 2 lines above: The parameters and arguments have a clear correspondence. Within the main function we called to addition passing two values: 5 and 3, that correspond to the int a and int b parameters declared for function addition. At the point at which the function is called from within main, the control is lost by main and passed to function addition. The value of both arguments passed in the call (5 and 3) are copied to the local variables int a and int b within the function. Function addition declares another local variable (int r), and by means of the expression r=a+b, it assigns to r the result of a plus b. Because the actual parameters passed for a and b are 5 and 3 respectively, the result is 8. The following line of code: return (r); finalizes function addition, and returns the control back to the function that called it in the first place (in this case, main). At this moment the program follows its regular course from the same point at which it was interrupted by the call to addition. But additionally, because the return statement in function addition specified a value: the content of variable r (return (r);), which at that moment had a value of 8. This value becomes the value of evaluating the function call. So being the value returned by a function the value given to the function call itself when it is evaluated, the variable z will be set to the value returned by addition (5, 3), that is 8. To explain it another way, you can imagine that the call to a function (addition (5,3)) is literally replaced by the value it returns (8). The following line of code in main is: printf("The result is %d", z); Important points about Functions āˆ’ Any C program contains at least one function. āˆ’ If a program contains only one function, it must be main( ). āˆ’ If a C program contains more than one function, then one (and only one) of these functions must be main( ), because program execution always begins with main( ). āˆ’ There is no limit on the number of functions that might be present in a C program. āˆ’ Each function in a program is called in the sequence specified by the function calls in main( ).
  • 3. Functions Intro to Programming MUHAMMAD HAMMAD WASEEM 3 āˆ’ After each function has done its thing, control returns to main( ).When main( ) runs out of function calls, the program ends. Well, letā€™s illustrate with an example. main( ) { printf ( "nI am in main" ) ; italy( ) ; printf ( "nI am finally back in main" ) ; } italy( ) { printf ( "nI am in italy" ) ; brazil( ) ; printf ( "nI am back in italy" ) ; } brazil( ) { printf ( "nI am in brazil" ) ; argentina( ) ; } argentina( ) { printf ( "nI am in argentina" ) ; } And the output would look like... I am in main I am in italy I am in brazil I am in argentina I am back in italy I am finally back in main Let us now summarize what we have learnt so far. a) C program is a collection of one or more functions. b) A function gets called when the function name is followed by a semicolon. For example, main( ) { argentina( ) ; } c) A function is defined when function name is followed by a pair of braces in which one or more statements may be present. For example, argentina( )
  • 4. Functions Intro to Programming MUHAMMAD HAMMAD WASEEM 4 { statement 1 ; statement 2 ; statement 3 ; } d) Any function can be called from any other function. Even main( ) can be called from other functions. For example, main( ) { message( ) ; } message( ) { printf ( "nCan't imagine life without C" ) ; main( ) ; } e) A function can be called any number of times. For example, main( ) { message( ) ; message( ) ; } message( ) { printf ( "nJewel Thief!!" ) ; } f) The order in which the functions are defined in a program and the order in which they get called need not necessarily be same. For example, main( ) { message1( ) ; message2( ) ; } message2( ) { printf ( "nBut the butter was bitter" ) ; } message1( ) { printf ( "nMary bought some butter" ) ; }
  • 5. Functions Intro to Programming MUHAMMAD HAMMAD WASEEM 5 g) A function can call itself. Such a process is called ā€˜recursionā€™. We would discuss this aspect of C functions later in this chapter. Types of Functions: There are basically two types of functions: 1. Library functions Ex. printf( ), scanf( ) etc. 2. User-defined functions Ex. argentina( ), brazil( ) etc. As the name suggests, library functions are nothing but commonly required functions grouped together and stored in what is called a Library. This library of functions is present on the disk and is written for us by people who write compilers for us. Almost always a compiler comes with a library of standard functions. The procedure of calling both types of functions is exactly same. Why Use Functions Why write separate functions at all? Why not squeeze the entire logic into one function, main( )? Two reasons: 1. Writing functions avoids rewriting the same code over and over. ļƒ˜ Suppose you have a section of code in your program that calculates area of a triangle. If later in the program you want to calculate the area of a different triangle, you wonā€™t like it if you are required to write the same instructions all over again. Instead, you would prefer to jump to a ā€˜section of codeā€™ that calculates area and then jump back to the place from where you left off. This section of code is nothing but a function. 2. Using functions it becomes easier to write programs and keep track of what they are doing. ļƒ˜ If the operation of a program can be divided into separate activities, and each activity placed in a different function, then each could be written and checked more or less independently. Separating the code into modular functions also makes the program easier to design and understand. Scope Rule of Functions Look at the following program main( ) { int i = 20 ; display ( i ) ; } display ( int j ) { int k = 35 ; printf ( "n%d", j ) ; printf ( "n%d", k ) ; } In this program is it necessary to pass the value of the variable i to the function display( )? Will it not become automatically available to the function display( )? No. Because by default the scope of a variable is local to the function in which it is defined. The presence of i is known only to the function main( ) and not to any other function. Similarly, the variable k is local to the function display( ) and hence it is not available to main( ). In general we can say that the scope of a variable is local to the function in which it is defined.
  • 6. Functions Intro to Programming MUHAMMAD HAMMAD WASEEM 6 Call by Value and Call by Reference By now we are well familiar with how to call functions. But, if you observe carefully, whenever we called a function and passed something to it we have always passed the ā€˜valuesā€™ of variables to the called function. Such function calls are called ā€˜calls by valueā€™. By this what we mean is, on calling a function we are passing values of variables to it. The examples of call by value are shown below: sum = calsum ( a, b, c ) ; f = factr ( a ) ; We have also learnt that variables are stored somewhere in memory. So instead of passing the value of a variable, can we not pass the location number (also called address) of the variable to a function? If we were able to do so it would become a ā€˜call by referenceā€™. What purpose a ā€˜call by referenceā€™ serves we would find out a little later. First we must equip ourselves with knowledge of how to make a ā€˜call by referenceā€™. This feature of C functions needs at least an elementary knowledge of a concept called ā€˜pointersā€™. So let us first acquire the basics of pointers after which we would take up this topic once again