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

More Related Content

Similar to Lecture 1_Functions in C.pptx

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 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
TeshaleSiyum
 

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

c.p function
c.p functionc.p function
c.p function
 
Functions
FunctionsFunctions
Functions
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
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
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
Basic information of function in cpu
Basic information of function in cpuBasic information of function in cpu
Basic information of function in cpu
 
Functions
FunctionsFunctions
Functions
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
Functions
Functions Functions
Functions
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
 
C functions list
C functions listC functions list
C functions list
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
Function
Function Function
Function
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
USER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfUSER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdf
 

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)

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.
 
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
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
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
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
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...
 
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
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
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
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
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
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 

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