We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 12
UNIT-04
FUNCTION
ve candividea large programinto the basic building blocks lnown es function, The function
contains the st of progranving statements enclosed by {}.
A function can be called multiple times to provide reusability and meulatity tothe C progam
nother worts, we can say that the collection of functions creates a program The function is
also known as procedureor subroutinein other programing languages.
Advantage of functions in C
‘There ae the following advantages of C functions.
By using functions, we can avoid rewtting same logicfcode again and again in
a progam
‘Weean call C functions any runiber of times ina program and from any place
inaprogam
Wecan track alarge G program easily whenit is divided into multiple
functions.
Rewsability isthe main achievement of C functions.
However; Function calling is always a overhead inaC program,
Function Aspects
‘There are three aspects of aC function,
+ Rumction declaration A funetion mst be declared globally in ac program to
tall the compiler about the function rame, fumetion parameters, and retum type.
Function call Function can be called from anywhere inthe program The
parameter list must not differ in function calling and function declaration, We must
pass the same nuntber of functions as it is declared inthe function declaration.
+ Function defirition ft contains the actual staterments which are to be executed.
Itis the most important aspect to which the control comes when the function is
called. Here, we must notice that only one value can be retured fromthe function,
‘SN Cfuncionaspects Syntax
7 Rinetion
1 decaration
retum type function_name (argument ist);
2 Fumwtioncall —_fumetion name (argument_list)
Scanned with CamScanner3 Rimetion——_retum_type function. nar (agument ist {function
@einition —_bely;}
‘The syntax of creating function in c language is given bow:
1. return_type function_name(data_type parameter...){
2. [/code to be executed
3. }
‘Types of Functions
‘There are two types of functions in C programing:
1, Library Functions: are the functions which are declared in the C header files
suchas scanf(), printf(), gets(), puts(), ceil, floor() ete.
2. User-defined functions: are the functions which are created by the C
‘programme, so tht he/she can use it many times It eluces the complexity of a big
rogramard optimizes the code.
Retum Value
AC function may or ray not retum a value fromthe function. I you dorit have to retum
any value fromthe function, use void for the retum type,
Let's see a simple example of C function that doestft retum any value fromthe function.
Example without retum value:
1. void hello(){
2. — printf("hello c");
3. +}
If you wart to retum any value fromthe function, you need to use any data type such as int,
Jong, char, etc. The retum type depends on the value to be retumad fromthe function.
Let's seea simple example of C function that retums int value fromthe function,
Example with return value,
1. int get()¢
2. return 10;
3
Inthe above exanple, we ave to retum 10 asa valu, so the return types int. If you want
to retum floating oirt value (e.g, 10.2, 3.1, 545, ec), you need touse float as the retum
‘ypeof the method.
1. float get(){
2. return 10.2;
3}
Now, you need to call the function, to get the value ofthe function.
Different aspects of function calling
cote ay Taxes oe seer ea may wate Bel
+ function without arguments and without retum value
function without arguments and with retum value
function with arguments and without rum value
function with arguments and with retum value
Scanned with CamScanner‘Exanple for Function without argurrent and retum value
\clude
void printame();
void main ()
{
5. printf("Hello ");
6. _ printName();
7.
8. void printName()
9
10. printf("Javatpoint");
i. }
Output
Hello Javatpoint
Example2
1. #include
2. void sum();
3. void main()
{
4,
5. printf("\nGoing to calculate the sum of two numbers:
6 — sum();
7
8. void sum()
9.
10, int a,b;
1. printf("\nénter two numbers");
2, scanf("%od %d" Ba, 8b);
13, __printf("The sum is %d",a+b);
14. }
Going to calculate the sum of two numbers:
Enter two numbers 10
24
The sum is 34
[Bxarrple for Function without argument and with retum value
Example
1. #include
2. int sum();
3. void main()
4
5. int result;
6. printf("\nGoing to calculate the sum of two number
7. result = sum();
8. printf("%d" result);
9}
10. int sum()
il. {
12. int a,b;
33. printf("\nenter two numbers");
4. scanf("%ed %d",8a,8b);
15, _ return a+b;
16. >
Scanned with CamScannerOutpat
Going to calculate the sum of two numbers:
Enter two numbers 10
24
The sum Is 34
‘Example 2: programto calculate the area of the square
1. #include
2. int sum();
3. void main()
4
5.” printf("Going to calculate the area of the square\n"
6 float area = square();
7 printf("The area of the square: %f\n" area);
8.
9.
4
ll. float side;
12. _printf("Enter the length of the side in meters: ");
13, scanf("%f",&side);
14, _ return side * side;
15. }
Output
Going to calculate the area of the square
Enter the length of the side in meters: 10
The area of the square: 100.000000
Example for Function with argument and without retum value
Exanple1
1. #include
2. void sum(int, int);
3. void main()
q
int 2,b,result;
printf("\nGoing to calculate the sum of two numbers:
printf("\nEnter two numbers:
scanf("%d %d" 8a, 8b);
sum(a,b);
PRM OMAL
10. }
11. void sum(int a, int b)
2 ¢
printf("\nThe sum is %d",a+
33.
14.
Output
Going to calculate the sum of two numbers:
Enter two numbers 10
24
The sum is 34
Scanned with CamScannerExample 2: programto calculate the average of five numbers.
1. #include
2. void average(int, int, int, int, int);
3. void main()
af
5. int a,b,c,d,e;
6 printf("\nGoing to calculate the average of five numbers:
7. printf("\nénter five numbers:");
8 ScaNF("%od %d Yd Yd %d",Ba,&b, 8c, 8d, Be);
9. average(a,b,c,d,e);
10. }
11. void average(int a, int b, int c, int d, int e)
12.
13, float ava;
V4. avg = (at+b+c+d+e)/5;
15. _printf("The average of given five numbers : %f",avg);
16. }
Output
Going to calculate the average of five numbers:
Enter five numbers: 10
20
30
40
50
The average of given five numbers : 30.000000
Example for Function with argument and with retum value
Example 1
1, #include
2. int sum(int, int);
3. void main()
4a {
5. int a,b,result;
6 printf("\nGoing to calculate the sum of two numbers:
7. printf("\nénter two numbers:");
8B scanf("%ed %d",&a,&b);
9. result = sum(a,b);
10. __printf("\nThe sum is : %d",result);
11.
12. int sum(int a, int b)
13. {
4. return a+b;
15.
Output
Going to calculate the sum of two numbers:
Enter two numbers:10
20
The sum is : 30
Scanned with CamScannerBxanple 2: Programto check whether a number is even or odd
1, #include
2. int even_odd(int);
3. void main()
4.
5. int nflag=0;
6. printf("\nGoing to check whether a number is even or odd");
7. printf("\nenter the number: ");
8 scanf("%d",8n);
9.
x
u
flag = even_odd(n);
0. if(flag
{
0)
printf("\nThe number is odd");
+
printf("\nThe number is even");
+
int even_odd(int n)
if(n%2 == 0)
{
return 1;
}
else
€
return 0;
+
9 to check whether a number is even or odd
Enter the number: 100
“The number is even
C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common
place called the library
Such furctions are use to performsore specific operations
For example, printf isa library function used to print onthe corsole. The libray functions
are created by the designers of compilers.
All C standard library functions are defined inside the different header files saved with the
extension h.
‘We need to include these header files in our program to rake use of the library functions
defined in such header files. te
For example, To use the lib functions suchas we noad toinclude stdiolhin
cur program hich isa header file that contains all the library functions regarding tarda
inpaifoutpet.
The listof measly used header files given in the following table.
Scanned with CamScanner1 ddigh | THiSi8 astandardingnt/outpat eader fle contains all the
brary functions regarding standard input/output.
2 conioch This is aconsole input/output header file,
contains all sting related library functions lke ges),
3 | stingh soe
4 | tdibh — THSbeater file contains all the general library functions like
alloc(), calloc(), exit), ete.
5 math __THiSbeader file contains ak the math operations related functions
like sqrt), pow), ec.
6 —timeh-—_This adr ile contains all the time related functions.
7 ype ‘This header file contains all character handling functions.
8 sida: Variable argument functions are defies inthis header fle.
9 sigalch All the signal harling functions are defined inthis header file,
10 seimph This file contains al the jump fimetions.
WL Iocalesh This ile contains locale functions.
12 emmh This file contains enor handling functions.
13. assert.h This file contains diagnostics functions,
Call by value and Call by reference in C
‘There are two methods to pass the daa into the fmetion in C language, i.e, call by
salve and call by reference,
‘Let's urlerstane call by value ane call by reference inc language one by one.
Call by valuein
Incall by value method, the value of the actual parameters is copied into the
formal parameters, Inother words, we can say thatthe value of the variable is used in
‘the function call inthe call by value method.
= __Incall by value method, we can not modify the value of the actual parameter
by the fol parameter.
Inca by value, different memory is allocated for actual and formal
parameters since the value of the actual parameter is copied into the formal
Parameter
+ ‘The actu parameters the argument which is used in the function cll
‘whereas formal parameter i the argument which is used inthe function defiition,
{ets ty to unerstand the concept of cal by value inclarguge bythe exanple given
low:
Scanned with CamScanner1. #include
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n" num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
& int x=100;
9. printf("Before function call x=%d \n", x);
10, change(x);//passing value in function
1. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
Call by Value Example: Swapping the values of the two variables
printf("Before swapping the values in main a = %d, b = %d\n",a,
); 1] printing the value of a and b in main
swap(a,b);
printf("After swapping values In main a = %d, b = %d\n",a,b); //
The value of actual parameters do not change by changing the formal pa
rameters in call by value, a = 10, b = 20
1, #include
2. void swap(int , int); //prototype of the function
3. int main’)
4a
5.“ inta = 10;
6 int b = 20;
7.
b)
8.
9.
10. }
11. void swap (int a, int b)
12.
13. int temp;
M4. temp =a;
15. 5
16. mp;
17. __ printf("After swapping values in function a = %d, b = %d\n",a,b)
3 // Formal parameters, a = 20, b = 10
18. }
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function
After swapping values in main a
Scanned with CamScannerCal by reference in
+ Incall by reference, the adress of the variables passed into the function call
asthe actual parameter.
‘The value of the actual parameters can be modified by changing the formal
parameters since the ackiress of the actual parameters is passed.
Incall by reference, the mempry allocations sinilar for both forral
anc actual parameters. All the operations inthe function are performed on
the value stored atthe acres ofthe actual parameters, and the modified value gets
stored atthe same ackess.
(Consider the following example forthe call by reference.
1. #include
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (#num) += 100;
5. printf ("After adding value inside function num=9%d \n", *num);
6.
7. imt main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&);//passing reference in function
iL. printf("After function call x=%d \n", x);
12. return 0;
13. 3
Output
Before function call x=100
Before adding value inside function nur
After adding value inside function num=200
After function call x=200
Call by reference Example: Swapping the values of the two variables
1, #include
2.
3. int main()
4
*); //prototype of the function
6
7,
b); // printing the value of a and b in main
8. swap(8a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); //
The values of actual parameters do change In call by reference, a = 10,
= 20
10. }
11. void swap (int *a, int *b)
12.
13, int temp;
14. temp = *a;
*a=*b;
Mp;
17, __printf("After swapping values in function a = %d, b = %d\n",*a,*
); // Formal parameters, a = 20, b = 10
18. +
Scanned with CamScannerOutput
Before swapping the values in main a = 10, b
‘After swapping values in function a = 20, b
After swapping values in main a = 20, b = 10
Difference between call by value and call by reference ine
(No. Call by value Call by reference
1 Acopyof thevalueis sed intothe Anadis of valueis pase info the
function function
(Changes rade inside the function is: Changes rade inside the function
— limited tothe function only. The ‘lidate outside ofthe function also,
2. values of the actual parameters do not ‘The values of the actual parameters do
change by changing the formal change by changing the formal
parameters. parameters.
‘Actual and formel arguments are
3 | crededat thedifferent menory Ausland formal arguments are created
tee atthe same menry location
Recursion in C
Recursionis the process which comes into existence when a function calls a copy of itslf to
workona smaller problem.
Any furction which calls itself is called recursive function, ane such function calls re
called recursive calls.
Recursion involves several numbers of recursive calls, However i s important to impose a
tenrination conttion of recursion,
Recursion codes shorter than iterative code however itis cific to understand.
Recursion cannot be applied to all the problem, but itis more useful for the tasks that can be
cefined in tem of sinaar subtasks. For Example, recursion may be applied to sorting,
searching, arc traversal probless.
Genera, iterative solutions are more efficient than recursion since function call is always
‘overhenl Any problem that canbe solved recursively, can also be solved iteratively.
‘However, some problems are best suited to be solved by the recursion, for example, tower
of Hare, Fiboreeci ses, factorial fein,
Intheflloving earpla neunion is waltocaledsete fl fara,
‘include
1
2. nt fact (int);
3. int mang)
4a
5. Intafi
6. printf"Enter the number whose factorial you want to ealeuate?");
7. scant");
Bo f= factiny:
9. pentfactorial = 86471);
1 >
LL, int actint 9)
a ¢
0)
Scanned with CamScannerInthe loiry comple esasienis wel to celae eft ofa nun
1. include
2. ntact (int);
3. int main()
a
5. int af
6. printfEnter the number whose Factorial you want to ealulate?");
7. seant(%e" An);
8 f= tack;
9. print factor = 0".
1. >
11. int octint np
2 ¢
13, Win==0)
wet
15. return;
6
17. elseit(
wot
, return 1
2.)
21. else
RB ¢
23, return nttact(n-1);
wy
2.)
Output
Enter the number whose factorial you want to calculate?S
factorial = 120
‘Wea ndaste he sbovopogramof tie rexnsive mill by the iguegiven dows
Recursive Function
A recursive function pefonms the tasks by dividing it nto the subtass. There isa
‘errination condition defined in the function which is satisfied by some specific subtask.
After this, the recursion stops and the final result is returned from the function,
“The case at wihich the function docsrt recuris called the base case whereas the instances
‘where the function keeps calli itself to paforma subiask, is called the recursive case. All
the recursive functions can be written using this format
Pseucoonde for writing any recursive function is given below.
1. If (test_for_base)
z ¢
3 return some_value;
4a}
5. else if (test_for_another_base)
6 ¢
7. ‘return some_another_value;
a)
9. else
0. {
LL, 7 statements;
Scanned with CamScanner‘Pseudocode for writing any recursive function is given below.
A. if (test_for_base)
2 {
3. return some_value;
4 >
5. else if (test_for_another_base)
&
7. return some_another_value;
8. ?
9. else
10. {
i. // Statements;
12. recursive call;
13.0 >
Example of recursion in C
Lats scean ecurple to find the nth tamof the Fiboracs series,
1. #include
2. int fbonacci(int);
3. void main ()
4a
5. ints;
6. Printf("Enter the value of n?");
7. seant(*%d" an);
8. f= fbonacci(n);
9. printt("easf):
10. }
11, int fibonacci (int n)
12 4
13. it (n==0)
wot
15. retumo;
6 +
17. elseif (n==1)
wt
1. return 1;
2. 4
21. else
2 4
2. return fibonacci(n-1)#fibonacci(n-2);
mw)
25.
Output
Enter the value of n?12
144
Scanned with CamScanner