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

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

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
 
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 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 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 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
 

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

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 

Recently uploaded (20)

INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 

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