SlideShare a Scribd company logo
C -
FUNCTION
OUTLINE
 What is C function?
 Uses of C functions
 C function declaration, function call and definition with example
program
 How to call C functions in a program?
 Call by value
 Call by reference
 C function arguments and return values
 C function with arguments and with return value
 C function with arguments and without return value
 C function without arguments and without return value
 C function without arguments and with return value
 Types of C functions
 Library functions in C
 User defined functions in C
 Creating/Adding user defined function in C library
 Command line arguments in C
 Variable length arguments in C
WHAT IS C FUNCTION?
 A function is a group of statements that together perform a task.
Every C program has at least one function, which is main().
 You can divide up your code into separate functions. How you
divide up your code among different functions is up to you, but
logically the division usually is so each function performs a
specific task.
 A function declaration tells the compiler about a function's
name, return type, and parameters. A
function definition provides the actual body of the function.
 The C standard library provides numerous built-in functions that
your program can call. For example, function printf() to print
output in the console.
 A function is known with various names like a method or a sub-
routine or a procedure, etc.
 Most languages allow you to create functions of some sort.
 Functions are used to break up large programs into named
sections.
 You have already been using a function which is the main
function.
 Functions are often used when the same piece of code has
to run multiple times.
 In this case you can put this piece of code in a function and
give that function a name. When the piece of code is
required you just have to call the function by its name. (So
you only have to type the piece of code once).
C - FUNCTIONS
C - FUNCTIONS
 In the example below we declare a function with the name
MyPrint.
 The only thing that this function does is to print the sentence:
“Printing from a function”.
 If we want to use the function we just have to call MyPrint()
and the printf statement will be executed.
DEFINING A FUNCTION
 The general form of a function definition is as follows:
 A function definition in C language consists of
 a function header and
 a function body.
 Here are all the parts of a function:
 Function Name: This is the actual name of the function. The
function name and the parameter list together constitute the
function signature.
 Parameters: A parameter is like a placeholder. When a function is
invoked, you pass a value to the parameter. This value is referred
to as actual parameter or argument. The parameter list refers to
the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no
parameters.
 Return Type: A function may return a value. The return type is
the data type of the value the function returns. If you don’t want to
return a result from a function, you can use void return type. Some
functions perform the desired operations without returning a value.
In this case, the return type is the keyword void.
 Function Body: The function body contains a collection of
statements that define what the function does.
PARTS OF A FUNCTION
EXAMPLE: FUNCTION
 Following is the source code for a function called max().
This function takes two parameters num1 and num2 and
returns the maximum between the two:
FUNCTION DECLARATIONS
 A function declaration(function prototype) tells the compiler
about a function name and how to call the function. The actual
body of the function can be defined separately.
 A function declaration has the following parts:
 For the above defined function max(), following is the function
declaration:
 Parameter names are not important in function declaration only
their type is required, so following is also valid declaration:
 Function declaration is required when you define a function in
one source file and you call that function in another file. In such
case you should declare the function at the top of the file
calling the function.
CALLING A FUNCTION
 While creating a C function, you give a definition of what the
function has to do. To use a function, you will have to call
that function to perform the defined task.
 When a program calls a function, program control is
transferred to the called function. A called function performs
defined task and when its return statement is executed or
when its function-ending closing brace is reached, it returns
program control back to the main program.
 To call a function, you simply need to pass the required
parameters along with function name, and if function returns
a value, then you can store returned value. For example:
CALLING A FUNCTION
CODE EXAMPLE: CALLING A FUNCTION
CODE EXAMPLE: CALLING A FUNCTION
A C program with
function declaration/fu
nction prototype.
FUNCTION ARGUMENTS
 C functions can accept an unlimited number of parameters.
 If a function is to use arguments, it must declare variables
that accept the values of the arguments. These variables
are called the formal parameters of the function.
 The formal parameters behave like other local variables
inside the function and are created upon entry into the
function and destroyed upon exit.
GLOBAL AND LOCAL VARIABLES
 Local variable:
 A local variable is a variable that is declared inside a function.
 A local variable can only be used in the function where it is
declared.
 Global variable:
 A global variable is a variable that is declared outside all
functions.
 A global variable can be used in all functions.
 See the following example( see the next slide )
 As you can see two
global variables are
declared, A and B.
These variables
can be used in
main() and Add().
 The local variable
answer can only
be used in main().
GLOBAL AND LOCAL VARIABLES
TYPE OF FUNCTION CALL
Call Type Description
Call by value This method copies the actual value of an argument into
the formal parameter of the function. In this case,
changes made to the parameter inside the function have
no effect on the argument.
Call by reference This method copies the address of an argument into the
formal parameter. Inside the function, the address is used
to access the actual argument used in the call. This
means that changes made to the parameter affect the
argument.
While calling a function, there are two ways that arguments
can be passed to a function:
CALL BY VALUE
 The call by value method of passing arguments to a
function copies the actual value of an argument into the
formal parameter of the function.
 In this case, changes made to the parameter inside the
function have no effect on the argument.
 By default, C programming language uses call by
value method to pass arguments. In general, this means
that code within a function cannot alter the arguments
used to call the function. Consider the
function swap() definition as follows.
CALL BY VALUE
 Consider the function swap() definition as follows.
CALL BY VALUE
 Now, let us call the function swap() by passing actual values as in the
following example:
Output:
The output shows that there is
no change in the values though
they had been changed inside
the function.
CALL BY REFERENCE
 The call by reference method of passing arguments to a
function copies the address of an argument into the
formal parameter.
 Inside the function, the address is used to access the
actual argument used in the call. This means that
changes made to the parameter affect the passed
argument.
 To pass the value by call by reference, argument pointers
are passed to the functions.
FUNCTION CALL BY REFERENCE
 To pass the value by reference, argument pointers are passed to
the functions just like any other value.
 So accordingly you need to declare the function parameters as
pointer types as in the following function swap(), which
exchanges the values of the two integer variables pointed to by
its arguments.
CALL BY REFERENCE
 Let us call the function swap() by passing values by reference as in the following
example:
Which shows that the
change has reflected
outside of the function as
well unlike call by value
where changes does not
reflect outside of the
function.
Output:
RECURSION
 Recursion is the process of repeating items in a self-similar way. Same
applies in programming languages as well where if a programming
allows you to call a function inside the same function that is called
recursive call of the function as follows.
 The C programming language supports recursion, i.e., a function to call
itself.
 But while using recursion, programmers need to be careful to define an
exit condition (base condition) from the function, otherwise it will go in
infinite loop.
 Recursive function are very useful to solve many mathematical
problems like to calculate factorial of a number, generating Fibonacci
series, etc.
NUMBER FACTORIAL
 Following is an example, which calculates factorial for a
given number using a recursive function:
FIBONACCI SERIES
 Following is another example, which generates Fibonacci
series for a given number using a recursive function:
 Function Example:
1. Implement the following Temperature conversion functions:
i) function Celsius returns the Celsius equivalent of a Fahrenheit
temperature, using the calculation:
celsius = 5.0 / 9.0 * ( fahrenheit - 32 );
ii) function Fahrenheit returns the Fahrenheit equivalent of a Celsius
temperature, using the calculation:
fahrenheit = 9.0 / 5.0 * (celsius + 32);
Use the functions from parts (i) and (ii) to write an application that enables the
user to choose either to enter a Fahrenheit temperature and display the Celsius
equivalent or to enter a Celsius temperature and display the Fahrenheit
equivalent.
#include<stdio.h>
#include<conio.h>
float Celsius(float F)
{
float c;
c=((F-32)*5)/9;
return c;
}
float Fahrenheit(float C)
{
float f;
f=((9*C)/5)+32;
return f;
}
int main()
{
char ch;
float cels, farn;
printf("nnWhich conversion you prefer?nnn");
printf(" 1.For Celsius to Fahrenheitn 2.For Fahrenheit to Celsius");
ch=getch();
switch(ch)
{
case '1':
printf("nnEnter temperature in Celsius: ");
scanf("%f",&cels);
farn=Fahrenheit(cels);
printf("nnConverted temperature in Fahrenheit: %f",farn);
break;
case '2':
printf("nnEnter temperature in Fahrenheit: ");
scanf("%f",&farn);
cels=Celsius(farn);
printf("nnConverted temperature in Celsius: %f",cels);
break;
default:
printf("nnWrong Choice....Have a good day!!");
break;
}
return 0;
}
2. Write codes for two functions named ArraySum and ArrayAvg with
appropriate parameter and return type to find out the sum and
average from an integer array. Call these functions from the main
function, pass the integer array and print the returned sum and
average in the main function.
 Hint: If you pass an array which has 3, 1, 4, 2, 5 as its elements than
ArraySum will return 15 and ArrayAvg will return 3.
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
int ArraySum(int *a,int Size)
{
int i,sum=0;
for(i=0;i<Size;i++)
{
sum=sum+*(a+i);
}
return sum;
}
float ArrayAvg(int *a,int Size)
{
int i;
float avg,sum=0;
for(i=0;i<Size;i++)
{
sum=sum+*(a+i);
}
avg = sum/Size;
return avg;
}
int main()
{
int N,sum,i,*Ary;
float avg;
printf("nnnHow many elements in your array??? ");
scanf("%d",&N);
Ary=(int*)malloc(sizeof(int)*N); //Dynamic Memory Allocation
printf("nnEnter %d Elements of your Arrayn",N);
for(i=0;i<N;i++)
{
scanf("%d",&Ary[i]);
}
sum=ArraySum(Ary,N);
printf("nnSum of Array Elements: %d",sum);
avg=ArrayAvg(Ary,N);
printf("nnAverage of Array Elements: %.3f",avg);
free(Ary);
getch();
return 0;
}

More Related Content

What's hot

Functions in c language
Functions in c language Functions in c language
Functions in c language
tanmaymodi4
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 
Operators in c programming
Operators in c programmingOperators in c programming
Operators in c programming
savitamhaske
 
Function in c
Function in cFunction in c
Function in c
savitamhaske
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
Anil Pokhrel
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
programming9
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
Appili Vamsi Krishna
 
Control statements
Control statementsControl statements
Control statements
Kanwalpreet Kaur
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
Srichandan Sobhanayak
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
C tokens
C tokensC tokens
C tokens
Manu1325
 
File in c
File in cFile in c
File in c
Prabhu Govind
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
v_jk
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
Sathish Narayanan
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
Harendra Singh
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.pptTareq Hasan
 
Function
FunctionFunction
Function
yash patel
 

What's hot (20)

Functions in c language
Functions in c language Functions in c language
Functions in c language
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Operators in c programming
Operators in c programmingOperators in c programming
Operators in c programming
 
Function in c
Function in cFunction in c
Function in c
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
Function
FunctionFunction
Function
 
Control statements
Control statementsControl statements
Control statements
 
Functions in C
Functions in CFunctions in C
Functions in C
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
C tokens
C tokensC tokens
C tokens
 
File in c
File in cFile in c
File in c
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
Function
FunctionFunction
Function
 

Similar to C functions

Functions in c language
Functions in c languageFunctions in c language
Functions in c language
Tanmay Modi
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
Rhishav Poudyal
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
zueZ3
 
Modular Programming in C
Modular Programming in CModular Programming in C
Modular Programming in C
bhawna kol
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
Mehul Desai
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
NirmalaShinde3
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
ArshiniGubbala3
 
unit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfunit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdf
JAVVAJI VENKATA RAO
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
Praveen M Jigajinni
 
Module 3-Functions
Module 3-FunctionsModule 3-Functions
Module 3-Functions
nikshaikh786
 
Functions in c++, presentation, short and sweet presentation, and details of ...
Functions in c++, presentation, short and sweet presentation, and details of ...Functions in c++, presentation, short and sweet presentation, and details of ...
Functions in c++, presentation, short and sweet presentation, and details of ...
Sar
 
[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++
Muhammad Hammad Waseem
 
4. function
4. function4. function
4. function
Shankar Gangaju
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
Bharath904863
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
SangeetaBorde3
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 FunctionDeepak Singh
 
Presentation 2.pptx
Presentation 2.pptxPresentation 2.pptx
Presentation 2.pptx
ziyadaslanbey
 
FUNCTION CPU
FUNCTION CPUFUNCTION CPU
FUNCTION CPU
Krushal Kakadia
 

Similar to C functions (20)

Functions in c language
Functions in c languageFunctions in c language
Functions in c language
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
 
Modular Programming in C
Modular Programming in CModular Programming in C
Modular Programming in C
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
unit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfunit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdf
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
Module 3-Functions
Module 3-FunctionsModule 3-Functions
Module 3-Functions
 
Functions in c++, presentation, short and sweet presentation, and details of ...
Functions in c++, presentation, short and sweet presentation, and details of ...Functions in c++, presentation, short and sweet presentation, and details of ...
Functions in c++, presentation, short and sweet presentation, and details of ...
 
Function
FunctionFunction
Function
 
[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++
 
4. function
4. function4. function
4. function
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
Presentation 2.pptx
Presentation 2.pptxPresentation 2.pptx
Presentation 2.pptx
 
FUNCTION CPU
FUNCTION CPUFUNCTION CPU
FUNCTION CPU
 

More from University of Potsdam

Computer fundamentals 01
Computer fundamentals 01Computer fundamentals 01
Computer fundamentals 01
University of Potsdam
 
Workshop on android apps development
Workshop on android apps developmentWorkshop on android apps development
Workshop on android apps development
University of Potsdam
 
Transparency and concurrency
Transparency and concurrencyTransparency and concurrency
Transparency and concurrency
University of Potsdam
 
Database System Architecture
Database System ArchitectureDatabase System Architecture
Database System Architecture
University of Potsdam
 
Functional dependency and normalization
Functional dependency and normalizationFunctional dependency and normalization
Functional dependency and normalization
University of Potsdam
 
indexing and hashing
indexing and hashingindexing and hashing
indexing and hashing
University of Potsdam
 
data recovery-raid
data recovery-raiddata recovery-raid
data recovery-raid
University of Potsdam
 
Query processing
Query processingQuery processing
Query processing
University of Potsdam
 
Machine Learning for Data Mining
Machine Learning for Data MiningMachine Learning for Data Mining
Machine Learning for Data Mining
University of Potsdam
 
Tree, function and graph
Tree, function and graphTree, function and graph
Tree, function and graph
University of Potsdam
 
Sonet
SonetSonet
Sets in discrete mathematics
Sets in discrete mathematicsSets in discrete mathematics
Sets in discrete mathematics
University of Potsdam
 
Set in discrete mathematics
Set in discrete mathematicsSet in discrete mathematics
Set in discrete mathematics
University of Potsdam
 
Series parallel ac rlc networks
Series parallel ac rlc networksSeries parallel ac rlc networks
Series parallel ac rlc networks
University of Potsdam
 
Series parallel ac networks
Series parallel ac networksSeries parallel ac networks
Series parallel ac networks
University of Potsdam
 
Relations
RelationsRelations
Relations
RelationsRelations
Propositional logic
Propositional logicPropositional logic
Propositional logic
University of Potsdam
 
Propositional logic
Propositional logicPropositional logic
Propositional logic
University of Potsdam
 
Prim algorithm
Prim algorithmPrim algorithm
Prim algorithm
University of Potsdam
 

More from University of Potsdam (20)

Computer fundamentals 01
Computer fundamentals 01Computer fundamentals 01
Computer fundamentals 01
 
Workshop on android apps development
Workshop on android apps developmentWorkshop on android apps development
Workshop on android apps development
 
Transparency and concurrency
Transparency and concurrencyTransparency and concurrency
Transparency and concurrency
 
Database System Architecture
Database System ArchitectureDatabase System Architecture
Database System Architecture
 
Functional dependency and normalization
Functional dependency and normalizationFunctional dependency and normalization
Functional dependency and normalization
 
indexing and hashing
indexing and hashingindexing and hashing
indexing and hashing
 
data recovery-raid
data recovery-raiddata recovery-raid
data recovery-raid
 
Query processing
Query processingQuery processing
Query processing
 
Machine Learning for Data Mining
Machine Learning for Data MiningMachine Learning for Data Mining
Machine Learning for Data Mining
 
Tree, function and graph
Tree, function and graphTree, function and graph
Tree, function and graph
 
Sonet
SonetSonet
Sonet
 
Sets in discrete mathematics
Sets in discrete mathematicsSets in discrete mathematics
Sets in discrete mathematics
 
Set in discrete mathematics
Set in discrete mathematicsSet in discrete mathematics
Set in discrete mathematics
 
Series parallel ac rlc networks
Series parallel ac rlc networksSeries parallel ac rlc networks
Series parallel ac rlc networks
 
Series parallel ac networks
Series parallel ac networksSeries parallel ac networks
Series parallel ac networks
 
Relations
RelationsRelations
Relations
 
Relations
RelationsRelations
Relations
 
Propositional logic
Propositional logicPropositional logic
Propositional logic
 
Propositional logic
Propositional logicPropositional logic
Propositional logic
 
Prim algorithm
Prim algorithmPrim algorithm
Prim algorithm
 

Recently uploaded

Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
Krisztián Száraz
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
JEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questionsJEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questions
ShivajiThube2
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
goswamiyash170123
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 

Recently uploaded (20)

Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
JEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questionsJEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questions
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 

C functions

  • 2. OUTLINE  What is C function?  Uses of C functions  C function declaration, function call and definition with example program  How to call C functions in a program?  Call by value  Call by reference  C function arguments and return values  C function with arguments and with return value  C function with arguments and without return value  C function without arguments and without return value  C function without arguments and with return value  Types of C functions  Library functions in C  User defined functions in C  Creating/Adding user defined function in C library  Command line arguments in C  Variable length arguments in C
  • 3. WHAT IS C FUNCTION?  A function is a group of statements that together perform a task. Every C program has at least one function, which is main().  You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is so each function performs a specific task.  A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.  The C standard library provides numerous built-in functions that your program can call. For example, function printf() to print output in the console.  A function is known with various names like a method or a sub- routine or a procedure, etc.
  • 4.  Most languages allow you to create functions of some sort.  Functions are used to break up large programs into named sections.  You have already been using a function which is the main function.  Functions are often used when the same piece of code has to run multiple times.  In this case you can put this piece of code in a function and give that function a name. When the piece of code is required you just have to call the function by its name. (So you only have to type the piece of code once). C - FUNCTIONS
  • 5. C - FUNCTIONS  In the example below we declare a function with the name MyPrint.  The only thing that this function does is to print the sentence: “Printing from a function”.  If we want to use the function we just have to call MyPrint() and the printf statement will be executed.
  • 6. DEFINING A FUNCTION  The general form of a function definition is as follows:  A function definition in C language consists of  a function header and  a function body.
  • 7.  Here are all the parts of a function:  Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.  Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.  Return Type: A function may return a value. The return type is the data type of the value the function returns. If you don’t want to return a result from a function, you can use void return type. Some functions perform the desired operations without returning a value. In this case, the return type is the keyword void.  Function Body: The function body contains a collection of statements that define what the function does. PARTS OF A FUNCTION
  • 8. EXAMPLE: FUNCTION  Following is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum between the two:
  • 9. FUNCTION DECLARATIONS  A function declaration(function prototype) tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.  A function declaration has the following parts:  For the above defined function max(), following is the function declaration:  Parameter names are not important in function declaration only their type is required, so following is also valid declaration:  Function declaration is required when you define a function in one source file and you call that function in another file. In such case you should declare the function at the top of the file calling the function.
  • 10. CALLING A FUNCTION  While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task.  When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.  To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. For example:
  • 12. CODE EXAMPLE: CALLING A FUNCTION
  • 13. CODE EXAMPLE: CALLING A FUNCTION A C program with function declaration/fu nction prototype.
  • 14. FUNCTION ARGUMENTS  C functions can accept an unlimited number of parameters.  If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.  The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.
  • 15. GLOBAL AND LOCAL VARIABLES  Local variable:  A local variable is a variable that is declared inside a function.  A local variable can only be used in the function where it is declared.  Global variable:  A global variable is a variable that is declared outside all functions.  A global variable can be used in all functions.  See the following example( see the next slide )
  • 16.  As you can see two global variables are declared, A and B. These variables can be used in main() and Add().  The local variable answer can only be used in main(). GLOBAL AND LOCAL VARIABLES
  • 17. TYPE OF FUNCTION CALL Call Type Description Call by value This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. Call by reference This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. While calling a function, there are two ways that arguments can be passed to a function:
  • 18. CALL BY VALUE  The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function.  In this case, changes made to the parameter inside the function have no effect on the argument.  By default, C programming language uses call by value method to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function. Consider the function swap() definition as follows.
  • 19. CALL BY VALUE  Consider the function swap() definition as follows.
  • 20. CALL BY VALUE  Now, let us call the function swap() by passing actual values as in the following example: Output: The output shows that there is no change in the values though they had been changed inside the function.
  • 21. CALL BY REFERENCE  The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter.  Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.  To pass the value by call by reference, argument pointers are passed to the functions.
  • 22. FUNCTION CALL BY REFERENCE  To pass the value by reference, argument pointers are passed to the functions just like any other value.  So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments.
  • 23. CALL BY REFERENCE  Let us call the function swap() by passing values by reference as in the following example: Which shows that the change has reflected outside of the function as well unlike call by value where changes does not reflect outside of the function. Output:
  • 24. RECURSION  Recursion is the process of repeating items in a self-similar way. Same applies in programming languages as well where if a programming allows you to call a function inside the same function that is called recursive call of the function as follows.  The C programming language supports recursion, i.e., a function to call itself.  But while using recursion, programmers need to be careful to define an exit condition (base condition) from the function, otherwise it will go in infinite loop.  Recursive function are very useful to solve many mathematical problems like to calculate factorial of a number, generating Fibonacci series, etc.
  • 25. NUMBER FACTORIAL  Following is an example, which calculates factorial for a given number using a recursive function:
  • 26.
  • 27.
  • 28. FIBONACCI SERIES  Following is another example, which generates Fibonacci series for a given number using a recursive function:
  • 29.  Function Example: 1. Implement the following Temperature conversion functions: i) function Celsius returns the Celsius equivalent of a Fahrenheit temperature, using the calculation: celsius = 5.0 / 9.0 * ( fahrenheit - 32 ); ii) function Fahrenheit returns the Fahrenheit equivalent of a Celsius temperature, using the calculation: fahrenheit = 9.0 / 5.0 * (celsius + 32); Use the functions from parts (i) and (ii) to write an application that enables the user to choose either to enter a Fahrenheit temperature and display the Celsius equivalent or to enter a Celsius temperature and display the Fahrenheit equivalent.
  • 30. #include<stdio.h> #include<conio.h> float Celsius(float F) { float c; c=((F-32)*5)/9; return c; } float Fahrenheit(float C) { float f; f=((9*C)/5)+32; return f; } int main() { char ch; float cels, farn; printf("nnWhich conversion you prefer?nnn"); printf(" 1.For Celsius to Fahrenheitn 2.For Fahrenheit to Celsius"); ch=getch(); switch(ch) { case '1': printf("nnEnter temperature in Celsius: "); scanf("%f",&cels); farn=Fahrenheit(cels); printf("nnConverted temperature in Fahrenheit: %f",farn); break; case '2': printf("nnEnter temperature in Fahrenheit: "); scanf("%f",&farn); cels=Celsius(farn); printf("nnConverted temperature in Celsius: %f",cels); break; default: printf("nnWrong Choice....Have a good day!!"); break; } return 0; }
  • 31. 2. Write codes for two functions named ArraySum and ArrayAvg with appropriate parameter and return type to find out the sum and average from an integer array. Call these functions from the main function, pass the integer array and print the returned sum and average in the main function.  Hint: If you pass an array which has 3, 1, 4, 2, 5 as its elements than ArraySum will return 15 and ArrayAvg will return 3.
  • 32. #include<stdio.h> #include<conio.h> #include<malloc.h> int ArraySum(int *a,int Size) { int i,sum=0; for(i=0;i<Size;i++) { sum=sum+*(a+i); } return sum; } float ArrayAvg(int *a,int Size) { int i; float avg,sum=0; for(i=0;i<Size;i++) { sum=sum+*(a+i); } avg = sum/Size; return avg; } int main() { int N,sum,i,*Ary; float avg; printf("nnnHow many elements in your array??? "); scanf("%d",&N); Ary=(int*)malloc(sizeof(int)*N); //Dynamic Memory Allocation printf("nnEnter %d Elements of your Arrayn",N); for(i=0;i<N;i++) { scanf("%d",&Ary[i]); } sum=ArraySum(Ary,N); printf("nnSum of Array Elements: %d",sum); avg=ArrayAvg(Ary,N); printf("nnAverage of Array Elements: %.3f",avg); free(Ary); getch(); return 0; }