SlideShare a Scribd company logo
FUNCTIONS IN C
Lecture 1
CSC-103 Programming Fundamentals
CSC-141 Introduction to Computer Programming
Slides prepared by: Dr. Shaista Jabeen
Lecture Outline
• What is a function?
• Types of functions
• Why do we need functions?
• Syntax of a function
• Main function
• Function declaration with an example
• Function definition with an example
• Function call (Hierarchical function calls)
• Functions with and without arguments
• Returning value from functions
• An Example Code
2
A Brief Review:
Structure of a C Program:
3
https://data-flair.training/blogs/basic-structure-of-c-program/
What is a function?
• Suppose you are building an application in C language and in one of
your program, you need to perform a same task more than once.
• In such case you have two options:
a) Use the same set of statements every time you want to perform the task
b) Create a function to perform that task, and just call it every time you need
to perform that task.
A function is a block of statements that performs a specific task.
4
Types of Functions
Predefined
Library functions
Declaration in header files
User-Defined
User customized functions,
to reduce complexity of
big programs
5
Types of Functions
1) Predefined - standard library functions such as puts(), gets(), printf(),
scanf() etc.
- These are the functions which already have a definition in header files (.h
files like stdio.h), so we just call them whenever there is a need to use them.
-we don’t define these functions
2) User Defined functions
- The functions that we create in a program are known as user defined
functions.
- There can be any number of user defined functions in a program.
6
Why do we need Functions?
7
• Reusability
• Function is defined only once -it can be called multiple times within the
program
• Organization:
• Dividing a big/complicated task into smaller code chunks
• Improved readability of code
• Easier Debugging
• Ease in testing – redundancy is reduced
• Extensibility
• When we need to extend our program to handle a case it didn’t handle
before; functions allow us to make the change in one place and have that
change take effect every time the function is called.
Example: A function to add two numbers
int addition (int num1, int num2)
{ int sum;
sum = num1+num2;
/* Function return type is integer, so we are returning an integer value, the sum of
the passed numbers. */
return sum;
}
Syntax of a function:
return_type function_name (argument list)
{
Set of statements – Block of code…
}
8
main function:
• A C program always starts execution with the main () function
• There is always one main function in a C program
• All other functions are called inside the main function with the
sequence specified
• When a function completes its task, the control returns to the main
function main ()
{ Statement1;
………
…….
Statement 100;
}
9
A simple Function: Example
#include<stdio.h>
void message(); //function prototype declaration
int main()
{
message(); // function call
printf(“this is the end of main functionn”);
return 0;
}
void message() // function definition
{
printf(“time is preciousn”);
}
10
Multiple functions Calls inside main ();
int main()
{
Function_1(); // function call
printf(“this is the end of first function”);
Function_2(); // function call
printf(“this is the end of second function”);
Function_3(); // function call
printf(“this is the end of third function”);
Function_4(); // function call
printf(“this is the end of fourth function”);
return 0;
}
Run Example in Code Blocks
(function definitions are given
there)
11
Elements Of User Defined Functions:
1. Function Prototype/Declaration
2. Function Definition
3. Function Call
12
Function Declaration or Prototype
• A function prototype is simply the declaration of a function that
specifies function's name, parameters and return type.
• It gives information to the compiler that the function may later be
used in the program.
Syntax:
returnType functionName (type1 argument1, type2 argument2, ...);
Example:
void display();
int addition (int , int );
Parameters List
13
Function Definition
It has two parts;
1. Function Header
• Function Name
• Function Type (return type)
• List of Parameters
• No semi-colon at the end
2. Function Body
• Local Variable Declarations
• Function Statements
• A return Statement
• All enclosed in curly braces
int function_name (void)
{ int x, y;
statements….
…..
return 0;
}
14
Function Definition: Example
• It contains the function body.
• Function body is the block of code to perform a specific task.
Example: (A function to add two numbers)
int sum (int num1, int num2)
{
int result;
result = num1+num2;
/* Function return type is integer, so we
are returning an integer value, the result
of the passed numbers. */
return result;
}
15
Function Header
Function Body
Function Call:
• A user-defined function is called from the main function.
• When a program calls a function, the program control is transferred
to the called function.
main()
{
………..
…………
funct_1();
…………
…………
}
return_type funct_1()
{
…………….
…………….
……………..
…………………
}
Calling Function
(Boss Function)
Called Function
(Worker Function) 16
Hierarchical Boss/Worker Function Relationship
Any called function can call another function and control passes between those two functions
in hierarchical manner.
main ()
Called function in first level
Called function in second level
17
Hierarchical Function Calling Example
int addition(int , int );
void display(int);
int main()
{
sum(4,5); // main is calling a user-defined function
return 0;
}
//__________________________________________________
int sum(int a, int b) // Called Function in First Level by main function
{ int y;
y=a+b;
display(y); // sum is calling another function display()
return 0;
} //__________________________________________________
void display(int z) // Called function in second level by sum function
{
printf("The sum of two numbers is %dn", z);
}
• A function called
inside main function
can call another
function.
• The control passes
between the calling
and called function
at each level of
hierarchy.
18
Funct_2();
Passing Arguments to/between Functions
• Arguments are used to communicate between the calling and the
called function
Functions
With
Arguments
//Function Declaration
int sum (int , int );
// Function Call
sum(10,20);
Without
Arguments
//Function Declaration
int display();
// Call
display();
19
Returning a value from function
A function may or may not return a
result. But if it does, we must use the
return statement to output the result.
return statement also ends the
function execution.
return statement can occur anywhere
in the function depending on the
program flow.
20
Function Example in Code Blocks
Example:
Take two points from user that define a point location in 2D cartesian co-
ordinate. Write a C program using functions to convert this point location to
polar coordinates.
Solution:
Domain Knowledge: Mathematics
• To convert from Cartesian Coordinates (𝑥, 𝑦)to Polar Coordinates 𝑟, 𝜃
𝑟 = (𝑥2+ 𝑦2
)
𝜃 = 𝑡𝑎𝑛−1
𝑦
𝑥
21
int main()
{
float x,y, theta, r;
printf("Enter a number for x coordinate: n");
scanf("%f", &x);
printf("Enter a number for y coordinate: n");
scanf("%f", &y);
r = distance(x,y); //calling function distance
theta = angle(x,y); //calling function angle
printf("The polar coordinates of %f and %f are; n r = %f n
theta = %f n", x,y,r, theta);
return 0;
}
float distance(float a, float b)
{ float d;
/* Calculating r */
d = sqrt(a*a + b*b);
return d;
}
C Code for Given Example:
22
Cartesian to Polar
Coordinates
Example:
23
float angle(float a, float b)
{ float ang,m;
m=b/a;
ang= atan(m);
/* Converting theta from radian to degrees */
printf("The angle in radians is %fn", ang);
ang= ang * (180/ PI);
/* Conditional Check for Polar angle */
if((a<0) && (b>0))
{ ang= 180 + ang;
return ang;
}
else if ((a>0) && (b<0))
{ ang = -(abs(ang));
return ang; }
else if ((a<0) && (b<0))
{ ang = 180 + ang;
return ang; }
else
return ang;
}
angle function in C:
Summarizing about Functions:
1) main() in C program is also a function.
2) A C program can have any number of functions, There is no limit on number
of functions. One of those functions must be a main function
3) Functions can be defined in any order
4) Function names in a program must be unique
5) A function gets called when the function name is followed by a semi-colon
6) A function cannot be defined inside a function.
24
Ad

More Related Content

Similar to Lecture 1_Functions in C.pptx (20)

C functions by ranjan call by value and reference.pptx
C functions by ranjan call by value and reference.pptxC functions by ranjan call by value and reference.pptx
C functions by ranjan call by value and reference.pptx
ranjan317165
 
c.p function
c.p functionc.p function
c.p function
giri5624
 
Functions
FunctionsFunctions
Functions
Lakshmi Sarvani Videla
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
ArshiniGubbala3
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
TeshaleSiyum
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
TeshaleSiyum
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
Lecture_5_-_Functions_in_C_Detailed.pptx
Lecture_5_-_Functions_in_C_Detailed.pptxLecture_5_-_Functions_in_C_Detailed.pptx
Lecture_5_-_Functions_in_C_Detailed.pptx
Salim Shadman Ankur
 
Basic information of function in cpu
Basic information of function in cpuBasic information of function in cpu
Basic information of function in cpu
Dhaval Jalalpara
 
c-Functions power point presentation on c functions
c-Functions power point presentation on c functionsc-Functions power point presentation on c functions
c-Functions power point presentation on c functions
10300PEDDIKISHOR
 
Functions
FunctionsFunctions
Functions
Pragnavi Erva
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
NirmalaShinde3
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
Sampath Kumar
 
Detailed concept of function in c programming
Detailed concept of function  in c programmingDetailed concept of function  in c programming
Detailed concept of function in c programming
anjanasharma77573
 
Functions
Functions Functions
Functions
Dr.Subha Krishna
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
JVenkateshGoud
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
Sowri Rajan
 
C functions list
C functions listC functions list
C functions list
Thesis Scientist Private Limited
 
User Defined Functionscccccccccccccccccccccccccc.pptx
User Defined Functionscccccccccccccccccccccccccc.pptxUser Defined Functionscccccccccccccccccccccccccc.pptx
User Defined Functionscccccccccccccccccccccccccc.pptx
233013812
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
Harendra Singh
 
C functions by ranjan call by value and reference.pptx
C functions by ranjan call by value and reference.pptxC functions by ranjan call by value and reference.pptx
C functions by ranjan call by value and reference.pptx
ranjan317165
 
c.p function
c.p functionc.p function
c.p function
giri5624
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
TeshaleSiyum
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
TeshaleSiyum
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
Lecture_5_-_Functions_in_C_Detailed.pptx
Lecture_5_-_Functions_in_C_Detailed.pptxLecture_5_-_Functions_in_C_Detailed.pptx
Lecture_5_-_Functions_in_C_Detailed.pptx
Salim Shadman Ankur
 
Basic information of function in cpu
Basic information of function in cpuBasic information of function in cpu
Basic information of function in cpu
Dhaval Jalalpara
 
c-Functions power point presentation on c functions
c-Functions power point presentation on c functionsc-Functions power point presentation on c functions
c-Functions power point presentation on c functions
10300PEDDIKISHOR
 
Detailed concept of function in c programming
Detailed concept of function  in c programmingDetailed concept of function  in c programming
Detailed concept of function in c programming
anjanasharma77573
 
User Defined Functionscccccccccccccccccccccccccc.pptx
User Defined Functionscccccccccccccccccccccccccc.pptxUser Defined Functionscccccccccccccccccccccccccc.pptx
User Defined Functionscccccccccccccccccccccccccc.pptx
233013812
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
Harendra Singh
 

Recently uploaded (20)

How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
Ad

Lecture 1_Functions in C.pptx

  • 1. FUNCTIONS IN C Lecture 1 CSC-103 Programming Fundamentals CSC-141 Introduction to Computer Programming Slides prepared by: Dr. Shaista Jabeen
  • 2. Lecture Outline • What is a function? • Types of functions • Why do we need functions? • Syntax of a function • Main function • Function declaration with an example • Function definition with an example • Function call (Hierarchical function calls) • Functions with and without arguments • Returning value from functions • An Example Code 2
  • 3. A Brief Review: Structure of a C Program: 3 https://data-flair.training/blogs/basic-structure-of-c-program/
  • 4. What is a function? • Suppose you are building an application in C language and in one of your program, you need to perform a same task more than once. • In such case you have two options: a) Use the same set of statements every time you want to perform the task b) Create a function to perform that task, and just call it every time you need to perform that task. A function is a block of statements that performs a specific task. 4
  • 5. Types of Functions Predefined Library functions Declaration in header files User-Defined User customized functions, to reduce complexity of big programs 5
  • 6. Types of Functions 1) Predefined - standard library functions such as puts(), gets(), printf(), scanf() etc. - These are the functions which already have a definition in header files (.h files like stdio.h), so we just call them whenever there is a need to use them. -we don’t define these functions 2) User Defined functions - The functions that we create in a program are known as user defined functions. - There can be any number of user defined functions in a program. 6
  • 7. Why do we need Functions? 7 • Reusability • Function is defined only once -it can be called multiple times within the program • Organization: • Dividing a big/complicated task into smaller code chunks • Improved readability of code • Easier Debugging • Ease in testing – redundancy is reduced • Extensibility • When we need to extend our program to handle a case it didn’t handle before; functions allow us to make the change in one place and have that change take effect every time the function is called.
  • 8. Example: A function to add two numbers int addition (int num1, int num2) { int sum; sum = num1+num2; /* Function return type is integer, so we are returning an integer value, the sum of the passed numbers. */ return sum; } Syntax of a function: return_type function_name (argument list) { Set of statements – Block of code… } 8
  • 9. main function: • A C program always starts execution with the main () function • There is always one main function in a C program • All other functions are called inside the main function with the sequence specified • When a function completes its task, the control returns to the main function main () { Statement1; ……… ……. Statement 100; } 9
  • 10. A simple Function: Example #include<stdio.h> void message(); //function prototype declaration int main() { message(); // function call printf(“this is the end of main functionn”); return 0; } void message() // function definition { printf(“time is preciousn”); } 10
  • 11. Multiple functions Calls inside main (); int main() { Function_1(); // function call printf(“this is the end of first function”); Function_2(); // function call printf(“this is the end of second function”); Function_3(); // function call printf(“this is the end of third function”); Function_4(); // function call printf(“this is the end of fourth function”); return 0; } Run Example in Code Blocks (function definitions are given there) 11
  • 12. Elements Of User Defined Functions: 1. Function Prototype/Declaration 2. Function Definition 3. Function Call 12
  • 13. Function Declaration or Prototype • A function prototype is simply the declaration of a function that specifies function's name, parameters and return type. • It gives information to the compiler that the function may later be used in the program. Syntax: returnType functionName (type1 argument1, type2 argument2, ...); Example: void display(); int addition (int , int ); Parameters List 13
  • 14. Function Definition It has two parts; 1. Function Header • Function Name • Function Type (return type) • List of Parameters • No semi-colon at the end 2. Function Body • Local Variable Declarations • Function Statements • A return Statement • All enclosed in curly braces int function_name (void) { int x, y; statements…. ….. return 0; } 14
  • 15. Function Definition: Example • It contains the function body. • Function body is the block of code to perform a specific task. Example: (A function to add two numbers) int sum (int num1, int num2) { int result; result = num1+num2; /* Function return type is integer, so we are returning an integer value, the result of the passed numbers. */ return result; } 15 Function Header Function Body
  • 16. Function Call: • A user-defined function is called from the main function. • When a program calls a function, the program control is transferred to the called function. main() { ……….. ………… funct_1(); ………… ………… } return_type funct_1() { ……………. ……………. …………….. ………………… } Calling Function (Boss Function) Called Function (Worker Function) 16
  • 17. Hierarchical Boss/Worker Function Relationship Any called function can call another function and control passes between those two functions in hierarchical manner. main () Called function in first level Called function in second level 17
  • 18. Hierarchical Function Calling Example int addition(int , int ); void display(int); int main() { sum(4,5); // main is calling a user-defined function return 0; } //__________________________________________________ int sum(int a, int b) // Called Function in First Level by main function { int y; y=a+b; display(y); // sum is calling another function display() return 0; } //__________________________________________________ void display(int z) // Called function in second level by sum function { printf("The sum of two numbers is %dn", z); } • A function called inside main function can call another function. • The control passes between the calling and called function at each level of hierarchy. 18 Funct_2();
  • 19. Passing Arguments to/between Functions • Arguments are used to communicate between the calling and the called function Functions With Arguments //Function Declaration int sum (int , int ); // Function Call sum(10,20); Without Arguments //Function Declaration int display(); // Call display(); 19
  • 20. Returning a value from function A function may or may not return a result. But if it does, we must use the return statement to output the result. return statement also ends the function execution. return statement can occur anywhere in the function depending on the program flow. 20
  • 21. Function Example in Code Blocks Example: Take two points from user that define a point location in 2D cartesian co- ordinate. Write a C program using functions to convert this point location to polar coordinates. Solution: Domain Knowledge: Mathematics • To convert from Cartesian Coordinates (𝑥, 𝑦)to Polar Coordinates 𝑟, 𝜃 𝑟 = (𝑥2+ 𝑦2 ) 𝜃 = 𝑡𝑎𝑛−1 𝑦 𝑥 21
  • 22. int main() { float x,y, theta, r; printf("Enter a number for x coordinate: n"); scanf("%f", &x); printf("Enter a number for y coordinate: n"); scanf("%f", &y); r = distance(x,y); //calling function distance theta = angle(x,y); //calling function angle printf("The polar coordinates of %f and %f are; n r = %f n theta = %f n", x,y,r, theta); return 0; } float distance(float a, float b) { float d; /* Calculating r */ d = sqrt(a*a + b*b); return d; } C Code for Given Example: 22
  • 23. Cartesian to Polar Coordinates Example: 23 float angle(float a, float b) { float ang,m; m=b/a; ang= atan(m); /* Converting theta from radian to degrees */ printf("The angle in radians is %fn", ang); ang= ang * (180/ PI); /* Conditional Check for Polar angle */ if((a<0) && (b>0)) { ang= 180 + ang; return ang; } else if ((a>0) && (b<0)) { ang = -(abs(ang)); return ang; } else if ((a<0) && (b<0)) { ang = 180 + ang; return ang; } else return ang; } angle function in C:
  • 24. Summarizing about Functions: 1) main() in C program is also a function. 2) A C program can have any number of functions, There is no limit on number of functions. One of those functions must be a main function 3) Functions can be defined in any order 4) Function names in a program must be unique 5) A function gets called when the function name is followed by a semi-colon 6) A function cannot be defined inside a function. 24
  翻译: