SlideShare a Scribd company logo
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

PDF
Constructors and destructors
PPTX
Function in C program
PPTX
Inline Functions and Default arguments
PPTX
Polymorphism In c++
PPTX
Inter Thread Communicationn.pptx
PPTX
Templates in C++
PPTX
Functions in c language
PPT
Data Structures with C Linked List
Constructors and destructors
Function in C program
Inline Functions and Default arguments
Polymorphism In c++
Inter Thread Communicationn.pptx
Templates in C++
Functions in c language
Data Structures with C Linked List

What's hot (20)

PPTX
Functions in c
PPT
Circular linked list
PPTX
INLINE FUNCTION IN C++
PPS
Wrapper class
PPTX
Friend functions
PPTX
Variables in C++, data types in c++
PPT
Inheritance C#
PPT
Stacks
PDF
Chapter2 Encapsulation (Java)
PPTX
Pointer arithmetic in c
PPTX
Functions in python slide share
PPTX
Binary expression tree
PPTX
Inheritance in java
PPTX
Static Data Members and Member Functions
PPT
Memory allocation in c
PPTX
Array in c++
PPTX
Inheritance in c++
PDF
Python functions
PDF
Constructor and Destructor
Functions in c
Circular linked list
INLINE FUNCTION IN C++
Wrapper class
Friend functions
Variables in C++, data types in c++
Inheritance C#
Stacks
Chapter2 Encapsulation (Java)
Pointer arithmetic in c
Functions in python slide share
Binary expression tree
Inheritance in java
Static Data Members and Member Functions
Memory allocation in c
Array in c++
Inheritance in c++
Python functions
Constructor and Destructor
Ad

Similar to Functions (20)

PPTX
Functions in c language
PPT
eee2-day4-structures engineering college
PPTX
Functionincprogram
PPTX
Fundamentals of functions in C program.pptx
PPTX
Function in c program
PPTX
Detailed concept of function in c programming
PPTX
C function
PPTX
PPTX
unit_2.pptx
PPT
Functions and pointers_unit_4
DOC
Unit 4 (1)
DOC
4. function
PPTX
unit_2 (1).pptx
PPTX
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
PPT
c-Functions power point presentation on c functions
PPT
Ch4 functions
PDF
VIT351 Software Development VI Unit1
PPT
RECURSION IN C
PPT
Recursion in C
PPT
Functions and pointers_unit_4
Functions in c language
eee2-day4-structures engineering college
Functionincprogram
Fundamentals of functions in C program.pptx
Function in c program
Detailed concept of function in c programming
C function
unit_2.pptx
Functions and pointers_unit_4
Unit 4 (1)
4. function
unit_2 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
c-Functions power point presentation on c functions
Ch4 functions
VIT351 Software Development VI Unit1
RECURSION IN C
Recursion in C
Functions and pointers_unit_4
Ad

Recently uploaded (20)

PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
master seminar digital applications in india
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Institutional Correction lecture only . . .
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
RMMM.pdf make it easy to upload and study
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Pre independence Education in Inndia.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
master seminar digital applications in india
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Institutional Correction lecture only . . .
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
RMMM.pdf make it easy to upload and study
O5-L3 Freight Transport Ops (International) V1.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPH.pptx obstetrics and gynecology in nursing
Supply Chain Operations Speaking Notes -ICLT Program
Pre independence Education in Inndia.pdf
Renaissance Architecture: A Journey from Faith to Humanism
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Final Presentation General Medicine 03-08-2024.pptx
VCE English Exam - Section C Student Revision Booklet
Abdominal Access Techniques with Prof. Dr. R K Mishra
human mycosis Human fungal infections are called human mycosis..pptx

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