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

Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
Alisha Korpal
 

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

Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
ankush_kumar
 

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

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 

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