SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Semelhante a Lecture 1_Functions in C.pptx

Semelhante a Lecture 1_Functions in C.pptx (20)

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
 
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
 

Último

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 

Último (20)

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 

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