SlideShare a Scribd company logo
1 of 25
Download to read offline
Functions in C
By
E.Pragnavi
Asst. Professor, MCA,
Dept. of CSE, UCE (A),
Osmania University
OUTLINE
 Introduction to Functions
 Properties of Functions
 Advantages of using Functions
 Types of functions
 Intercommunication among Functions
What is a Function?
 A function in C language is a block of code that performs a
specific task.
 It has a name and it is reusable i.e. it can be executed from as
many different parts in a C Program as required.
 It also optionally returns a value to the calling program
Properties of Function
 Every function has a unique name.
 This name is used to call function from “main()”
function. A function can be called from within another
function.
 A function performs a specific task.
 A task is a distinct job that your program must perform as
a part of its overall operation, such as sorting an array,
etc.,
 A function returns a value to the calling program.
 This is optional and depends upon the task your function
is going to accomplish.
Advantages of using Functions
 It makes programs significantly easier to understand.
 Even without software engineering, functions allow the structure of the
program to reflect the structure of its application.
 The main program can consist of a series of function calls rather than
countless lines of code.
 Well written functions may be reused in multiple programs
Enables code sharing
The C standard library is an example
 Functions can be used to protect data (esp. Local data)
 Easy to locate and isolate faulty functions.
Types of Functions
 C language is collection of various inbuilt functions.
 They are written in the header files
 To use them appropriate header files should be included in the
source code
Header Files Functions Defined
stdio.h printf(), scanf(), getchar(), putchar(),
gets(), puts(), fopen(), fclose()
conio.h clrscr(), getch()
ctype.h Toupper(), tolower(), isalpha()
Math.h pow(), Sqrt(), cos(), log()
Stdlib.h Rand(), exit()
String.h strlen(), strcpy(), strupr()
User Defined Functions
 General structure of a function
<return type> FunctionName (Argument1, Argument2, Argument3......)
{
Statement1;
Statement2;
Statement3;
}
Example of a function:
int sum (int x, int y)
{
int result;
result = x + y;
return (result);
}
Function Prototype Declaration
 A user-written function should normally be declared prior to its use.
 The general form of this function declaration statement is as follows:
<return type> FunctionName (data_type_list);
 There are three basic parts in the declaration.
 Function Name: it is the name of the function and follows the
same naming rules as that for any valid variable in C.
 Return type: it specifies the type of data given back to the calling
construct by the function after it executes its specific task.
 data_type_list: the list specifies the data type of each of the
variables.
Function Prototype Declaration (Contd..)
 Examples of declaration statements:
a) float tempcon(float celsius);
b) double power( double, int);
c) int fact(int);
d) void display(void);
 If there are no parameters to a function, you can specify the parameter
list as void.
 The name of a function is global.
 Semicolon is required at the end of a function protoype.
 If the number and order of arguments does not agree with the number
of parameters specified in the prototype, the behavior is undefined.
Function Definition
 The collection of program statements that describes the specific task.
 It consists of the function header and a function body, which is a block of
code enclosed in paranthesis.
 The definition creates the actual function in memory.
 The general form of function definition is:
return_type function_name(data_type variable1, data_type variable2,..)
{
/* Function body */
}
 The function header in this definition is
 return_type function_name(data_type variable1, data_type variable2,..)
 Function header is similar to the function declaration but does not require the
semicolon at the end.
 The list of variables in the function header is also referred to as the formal
parameters.
Function Call
 A function will carry out its expected action whenever it is invoked (i.e, called).
 The program control passes to that of the called function.
 Once the function completes its task, the program control is returned back to the
calling function.
 The general form of the function call statement is
function_name(variable1, variable2,..)
or
variable_name= function_name(variable1, variable2,..)
• A function will process information passed to it and return a single value.
 If there are no arguments to be passed in the function, then the calling statement
would be
function_name();
or
variable_name=function_name();
 Information will be passed to the function via special identifiers or expression called
argumensts or actual parameters and returned through return statement.
Example
return statement
 The general form of the return statement is:
return expression;
or
return(expression);
 where expression evaluates to a value of the type specified in
the function header for the return value.
 The expression can also include function calls, for e.g.,
x=power(power(2,5),2);
 if a function returns a value , it has to be assigned to some
variable since a value is being returned.
return statement example
 There may be more than one return statement in a function but only
one return statement will be executed per calling to the function.
• Function definition to check whether a given year is a leap year or not.
void leap_year(int year)
{
if(((year%4==0) && (year%100!=0))|| (year%400==0))
return 1;
else
return 0;
}
Inter Function Communication
• Communication between calling and called function is done
through exchange of data.
• The flow of data is divided into 3 strategies:
 Downward flow: from the calling to called function
 Upward flow: from the called to calling function
 Bidirectional flow: in both the directions
• Implementation of Inter function communication is done through
3 strategies:
 Pass by value
 pass by reference
 return
• C language uses only pass by value and return to achieve the
above types of communication
Function with no argument and no return
• In this the calling function sends data to the called function.
• No data flows in the opposite direction
• Copies of the data items are passed from the calling function
to the called function
• The called function may change the values passed, but the
original values in the calling function remain unchanged.
• Example of this type is function with arguments but no
return statement.
Downward flow
Function with arguments and no return
It occurs when the called function sends data back to the called function without
receiving any data from it.
Example of this type is function with no arguments but return statement
Upward Flow
Bi-direction Communication
Example of this type is Function with arguments and return
 While the previous example works well for only one data item to be returned.
 C does not allow us to directly reference a variable in the calling function for
returning multiple data items.
 The solution is for the calling function to pass the address of the variable to the called
function.
 Given the variables address the called function can then put the data in the calling
function. So the called function needs a special type of variable called pointer
variable, that points to the variable in the called function.
Example: function_name(&variable1, &variable2); // calling function
void function_name(int *variable1, int* variable2); //called function
 The called function needs to declare that the parameter is to receive an address, we
use asterisk which signifies that the variables are address variables holding the
address.
 Accessing the variable indirectly through its address stored in the parameter list
through * (asterisk) is know as indirection operator.
Function that return multiple values
Example : Function that return multiple values
#include<stdio.h>
#include<conio.h>
void calc(int x, int y, int *add, int *sub)
{
*add = x+y;
*sub = x-y;
}
void main()
{
int a=20, b=11, p,q;
clrscr();
calc(a,b,&p,&q);
printf("Sum = %d, Sub = %d",p,q);
getch();
}
Example for call by reference
 A recursive function is one that calls itself directly or indirectly to solve
a smaller version of its task until a final call which does not require a
self-call.
 It is like a top down approach
 Every recursive function must have atleast one base case.
 The statement that solves the problem is known as base case, the rest of
the function is known as general case.
 For example: In factorial using recursion example,
 the base case is factorial(0) or factorial(1) ;
 the general case is n* factorial(n-1). It contains the logic needed to
reduce the size of the problem
Recursive Functions
Example: factorial of a number using recursion
#include <stdio.h>
int factorial(int);
int main()
{
int num;
int result;
printf("Enter a number to find it's Factorial: ");
scanf("%d", &num);
if (num < 0)
{
printf("Factorial of negative number not possiblen");
}
else
{
result = factorial(num);
printf("The Factorial of %d is %d.n", num, result);
}
return 0;
}
int factorial(int num)
{
if (num == 0 || num == 1)
{
return 1;
}
else
{
return(num * factorial(num - 1));
}
}

More Related Content

What's hot

Function in c language(defination and declaration)
Function in c language(defination and declaration)Function in c language(defination and declaration)
Function in c language(defination and declaration)VC Infotech
 
functions in C and types
functions in C and typesfunctions in C and types
functions in C and typesmubashir farooq
 
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
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functionsAlisha Korpal
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C v_jk
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Presentation on function
Presentation on functionPresentation on function
Presentation on functionAbu Zaman
 
Functions in c
Functions in cFunctions in c
Functions in cInnovative
 
Pointers and call by value, reference, address in C
Pointers and call by value, reference, address in CPointers and call by value, reference, address in C
Pointers and call by value, reference, address in CSyed Mustafa
 

What's hot (20)

lets play with "c"..!!! :):)
lets play with "c"..!!! :):)lets play with "c"..!!! :):)
lets play with "c"..!!! :):)
 
Function in c
Function in cFunction in c
Function in c
 
Function
FunctionFunction
Function
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Function in c language(defination and declaration)
Function in c language(defination and declaration)Function in c language(defination and declaration)
Function in c language(defination and declaration)
 
functions in C and types
functions in C and typesfunctions in C and types
functions in C and types
 
C function presentation
C function presentationC function presentation
C function presentation
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Function in C
Function in CFunction in C
Function in C
 
C functions
C functionsC functions
C functions
 
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
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Pointers and call by value, reference, address in C
Pointers and call by value, reference, address in CPointers and call by value, reference, address in C
Pointers and call by value, reference, address in C
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 

Similar to Functions (20)

Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
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
 
Functions
Functions Functions
Functions
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Functions
FunctionsFunctions
Functions
 
FUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdfFUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdf
 
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
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
4. function
4. function4. function
4. function
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
 
C functions list
C functions listC functions list
C functions list
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
Functions
FunctionsFunctions
Functions
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
 
Function
Function Function
Function
 
Functions in c language
Functions in c languageFunctions in c language
Functions in c language
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 

Recently uploaded

week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsPooky Knightsmith
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 

Recently uploaded (20)

week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young minds
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 

Functions

  • 1. Functions in C By E.Pragnavi Asst. Professor, MCA, Dept. of CSE, UCE (A), Osmania University
  • 2. OUTLINE  Introduction to Functions  Properties of Functions  Advantages of using Functions  Types of functions  Intercommunication among Functions
  • 3. What is a Function?  A function in C language is a block of code that performs a specific task.  It has a name and it is reusable i.e. it can be executed from as many different parts in a C Program as required.  It also optionally returns a value to the calling program
  • 4. Properties of Function  Every function has a unique name.  This name is used to call function from “main()” function. A function can be called from within another function.  A function performs a specific task.  A task is a distinct job that your program must perform as a part of its overall operation, such as sorting an array, etc.,  A function returns a value to the calling program.  This is optional and depends upon the task your function is going to accomplish.
  • 5. Advantages of using Functions  It makes programs significantly easier to understand.  Even without software engineering, functions allow the structure of the program to reflect the structure of its application.  The main program can consist of a series of function calls rather than countless lines of code.  Well written functions may be reused in multiple programs Enables code sharing The C standard library is an example  Functions can be used to protect data (esp. Local data)  Easy to locate and isolate faulty functions.
  • 6. Types of Functions  C language is collection of various inbuilt functions.  They are written in the header files  To use them appropriate header files should be included in the source code Header Files Functions Defined stdio.h printf(), scanf(), getchar(), putchar(), gets(), puts(), fopen(), fclose() conio.h clrscr(), getch() ctype.h Toupper(), tolower(), isalpha() Math.h pow(), Sqrt(), cos(), log() Stdlib.h Rand(), exit() String.h strlen(), strcpy(), strupr()
  • 7. User Defined Functions  General structure of a function <return type> FunctionName (Argument1, Argument2, Argument3......) { Statement1; Statement2; Statement3; } Example of a function: int sum (int x, int y) { int result; result = x + y; return (result); }
  • 8. Function Prototype Declaration  A user-written function should normally be declared prior to its use.  The general form of this function declaration statement is as follows: <return type> FunctionName (data_type_list);  There are three basic parts in the declaration.  Function Name: it is the name of the function and follows the same naming rules as that for any valid variable in C.  Return type: it specifies the type of data given back to the calling construct by the function after it executes its specific task.  data_type_list: the list specifies the data type of each of the variables.
  • 9. Function Prototype Declaration (Contd..)  Examples of declaration statements: a) float tempcon(float celsius); b) double power( double, int); c) int fact(int); d) void display(void);  If there are no parameters to a function, you can specify the parameter list as void.  The name of a function is global.  Semicolon is required at the end of a function protoype.  If the number and order of arguments does not agree with the number of parameters specified in the prototype, the behavior is undefined.
  • 10. Function Definition  The collection of program statements that describes the specific task.  It consists of the function header and a function body, which is a block of code enclosed in paranthesis.  The definition creates the actual function in memory.  The general form of function definition is: return_type function_name(data_type variable1, data_type variable2,..) { /* Function body */ }  The function header in this definition is  return_type function_name(data_type variable1, data_type variable2,..)  Function header is similar to the function declaration but does not require the semicolon at the end.  The list of variables in the function header is also referred to as the formal parameters.
  • 11. Function Call  A function will carry out its expected action whenever it is invoked (i.e, called).  The program control passes to that of the called function.  Once the function completes its task, the program control is returned back to the calling function.  The general form of the function call statement is function_name(variable1, variable2,..) or variable_name= function_name(variable1, variable2,..) • A function will process information passed to it and return a single value.  If there are no arguments to be passed in the function, then the calling statement would be function_name(); or variable_name=function_name();  Information will be passed to the function via special identifiers or expression called argumensts or actual parameters and returned through return statement.
  • 13. return statement  The general form of the return statement is: return expression; or return(expression);  where expression evaluates to a value of the type specified in the function header for the return value.  The expression can also include function calls, for e.g., x=power(power(2,5),2);  if a function returns a value , it has to be assigned to some variable since a value is being returned.
  • 14. return statement example  There may be more than one return statement in a function but only one return statement will be executed per calling to the function. • Function definition to check whether a given year is a leap year or not. void leap_year(int year) { if(((year%4==0) && (year%100!=0))|| (year%400==0)) return 1; else return 0; }
  • 15. Inter Function Communication • Communication between calling and called function is done through exchange of data. • The flow of data is divided into 3 strategies:  Downward flow: from the calling to called function  Upward flow: from the called to calling function  Bidirectional flow: in both the directions • Implementation of Inter function communication is done through 3 strategies:  Pass by value  pass by reference  return • C language uses only pass by value and return to achieve the above types of communication
  • 16. Function with no argument and no return
  • 17. • In this the calling function sends data to the called function. • No data flows in the opposite direction • Copies of the data items are passed from the calling function to the called function • The called function may change the values passed, but the original values in the calling function remain unchanged. • Example of this type is function with arguments but no return statement. Downward flow
  • 18. Function with arguments and no return
  • 19. It occurs when the called function sends data back to the called function without receiving any data from it. Example of this type is function with no arguments but return statement Upward Flow
  • 20. Bi-direction Communication Example of this type is Function with arguments and return
  • 21.  While the previous example works well for only one data item to be returned.  C does not allow us to directly reference a variable in the calling function for returning multiple data items.  The solution is for the calling function to pass the address of the variable to the called function.  Given the variables address the called function can then put the data in the calling function. So the called function needs a special type of variable called pointer variable, that points to the variable in the called function. Example: function_name(&variable1, &variable2); // calling function void function_name(int *variable1, int* variable2); //called function  The called function needs to declare that the parameter is to receive an address, we use asterisk which signifies that the variables are address variables holding the address.  Accessing the variable indirectly through its address stored in the parameter list through * (asterisk) is know as indirection operator. Function that return multiple values
  • 22. Example : Function that return multiple values #include<stdio.h> #include<conio.h> void calc(int x, int y, int *add, int *sub) { *add = x+y; *sub = x-y; } void main() { int a=20, b=11, p,q; clrscr(); calc(a,b,&p,&q); printf("Sum = %d, Sub = %d",p,q); getch(); }
  • 23. Example for call by reference
  • 24.  A recursive function is one that calls itself directly or indirectly to solve a smaller version of its task until a final call which does not require a self-call.  It is like a top down approach  Every recursive function must have atleast one base case.  The statement that solves the problem is known as base case, the rest of the function is known as general case.  For example: In factorial using recursion example,  the base case is factorial(0) or factorial(1) ;  the general case is n* factorial(n-1). It contains the logic needed to reduce the size of the problem Recursive Functions
  • 25. Example: factorial of a number using recursion #include <stdio.h> int factorial(int); int main() { int num; int result; printf("Enter a number to find it's Factorial: "); scanf("%d", &num); if (num < 0) { printf("Factorial of negative number not possiblen"); } else { result = factorial(num); printf("The Factorial of %d is %d.n", num, result); } return 0; } int factorial(int num) { if (num == 0 || num == 1) { return 1; } else { return(num * factorial(num - 1)); } }