You are on page 1of 31

Unit 2: C Functions:

Topics Covered:
1. declaration, definition and scope,
2. recursion,
3. call by value, call by reference.

C by Dr. Deepika Bhatia 1


Functions: Definition & Advantages
A function is a block of code defined to perform a particular task.{…..}.
We can break programinto smallersegments called functions.
Codeofonefunction is hiddenfromotherfunctions.
2 categories of function:
1. Library functions (predefined, sqrt()) 2. User defined functions
Advantages of using functions: (Why use functions?)

• Length of the source program isreduced.


• Easyto locate and debugerrors.
• Savesdebugging time
• Afunction can be used by many other programs.
• It facilitates top to down modular approach.
• Promotes reusability of code. (not needed to rewrite the
codeifa task is repetitivelyperformed)
C by Dr. Deepika Bhatia 2
Top –down modular approach

C by Dr. Deepika Bhatia 3


Multi Function ProgramStructure

C by Dr. Deepika Bhatia 4


Tips about function

C by Dr. Deepika Bhatia 5


Tips about function

C by Dr. Deepika Bhatia 6


Elements of User Defined Functions
1. Function Declaration
2. Function Call
3. Function Definition-// body define
Function definition includes the following:
1. Function name
2. Function Type Function header
3. List of Parameters
4. Local Variabledeclarations
5. Function statements Function Body
6. A return statement

C by Dr. Deepika Bhatia 7


Function declaration/prototype
Syntax:

return_datatype function_name(datatype var1, datatype var2……..);

Example:
float avg(int a, int b);
void swap(int , int); //argument name optional
void swap(int x, int y);
swap(int,int); //default return type is int

C by Dr. Deepika Bhatia 8


Function Definition
Function definition includes:
A. Function header:
1. Function name
2. Function Type
3. List of Parameters
B. Function Body
4. Local Variabledeclarations
5. Function statements
6. A return statement

Function Call/ Invoke/ Executed


Syntax:
Function_name(var1,var2,----);

Argruments can be variable name, expressions, constants


9
Example: add() function is created to find sum of 2
integers

C by Dr. Deepika Bhatia 10


C by Dr. Deepika Bhatia 11
//C program to find area of circle using function
#include <math.h>
#include <stdio.h>
#define PI 3.142

double Area(int r)
{
return PI * pow(r, 2);
}

int main()
{
printf("Area is %f", Area(5));
return 0;
}

C by Dr. Deepika Bhatia 12


Type of functions:

1. Function with no argument and no return


2. Function with argument and noreturn
3. Function with argument andreturn
4. Function with no argument and return

C by Dr. Deepika Bhatia 13


Two way data communication between function
1. Function with no argument and no return

C by Dr. Deepika Bhatia 14


Function with no arguments and no return value
#include<stdio.h>
void add(); // function declaration
void main()
{
add(); //function call
}
void add()
{ //function definition
int a,b,c;
printf(“enter numbers to be added”);
scanf(“%d %d”, &a, &b);// 10 34
c=a+b; // 10 ,34
printf(“result=%d”,c);

}
C by Dr. Deepika Bhatia 15
2. Function with Arguments and no return value

void add(int c,int d); // function declaration


void main() //function arguments / parameters
{
int a,b;
printf(“enter numbers to be added”);
scanf(“%d %d”, &a, &b); // 10 34
add(a,b); // function call ,add(10,34) , a and b Actual Argument
}
void add(int c, int d) // (10,34) , c and d FormalAgrument
{
int e; // function definition

e=c+d; // 10 ,34
printf(“result=%d”,e);
}
C by Dr. Deepika Bhatia 16
Tips
1.Type , order and number of actual and formal arguments must always besame.
2. It is not compulsory to usevariable names in the prototype declaration.
void sum(int , int);
3.No separatereturn statement was necessary to sendcontrol back
4. If the value of formal argument changed in the function the corresponding
change does not takeplacein the callingfunction

C by Dr. Deepika Bhatia 17


3. Function with Argument & Return Statement
float add(float,float); // function declaration
void main()
{
float a,b,s;
printf(“enter numbers to be added”);
scanf(“%f %f”, &a, &b); // 10 34 main
s=add(a,b); function
printf(“Sum=%f”,s); definition
}
float add(float c, float d) // (10,34) //return type of a function, formal
{
float e;
add function definition
e=a+b; // 10 ,34
return e;
}

C by Dr. Deepika Bhatia 18


return statement

1.On executing the return statement , it immediately


transfer the control back to the calling function
2. It returns the value present in the parentheses after return
to the calling function
3.There is no restriction on the number of return statements in a
function but A function can return only one value at a time.
For eg: to find largest of two numbers

C by Dr. Deepika Bhatia 19


4. Function with no argument and return
int num(void);
void main()
{
int m=num();
printf(“%d”,m);
}
int num(void)
{
int n;
scanf(“%d”,&n);
return(n);
}
C by Dr. Deepika Bhatia 20
Question
1) WAPto calculate simple interest using functions.

2) WAPto check whether a number is an Armstrong number or not


using functions with return value.

3)WAPto calculate factorial of a number using functions with


return statement.

C by Dr. Deepika Bhatia 21


Recursion: Definition & Conditions
Recursion is aprocess in which afunction calls itself. (i.e does recursive calls)
Used in sorting, searching etc. type of problems.
Necessary Conditions for recursion:
1. Basecase tostopit. eg:n==0incase offactorial
2. Recursive case ( f act(n)= n*fact( n - 1) )
void main()
{
sum();
}
void sum() // recursive function
{ ……..
sum(); Note: A program is called recursive when an
} entity calls itself. A program is call iterative
when there is a loop (or repetition eg: for
loop).
C by Dr. Deepika Bhatia 22
Recursion Example:
n! = n * (n – 1)!
WAP to find FACTORIAL of number n! = 1 if n = 0 or n = 1
#include <stdio.h> Output:
unsigned int factorial(unsigned int n) Factorial of 3 is 6
{
if (n == 0)
int main()
return 1;
{
else
int num = 3;
return n * factorial(n - 1);
printf("Factorial of %d is %d",
}
num, factorial(num));
return 0;
C by Dr. Deepika Bhatia 23
}
Question

Logic of findingfactorialof a number is shown in abovepicture.

WAPto print the termsCofFibonacci series using recursion. 24


by Dr. Deepika Bhatia
Call by Value in C
#include<stdio.h>
void add(int num)
{
num=num+10;
printf("Inside function %d\n",num);
}
int main()
{
Call by value: int x=10;
1. Value of actual parameter copied into formal. add(x);
2. Cant modify actual parameters value using printf("After function call %d \n", x);
formal parameter. return 0;
3. Different memory allocated to actual and }
formal parameters as value of actual copied Output: Inside function 20
into formal. After function call 10 25
Call by Reference in C
Call by Reference: #include<stdio.h>

1. We don’t pass value, we pass address. void add(int *num) //pointer num
Address of var. is passed into function call as {
actual parameter. *num=*num+10; //value at num

2. As address is passed, so value of actual printf("Inside function %d\n",*num);


parameter can be modified by changing }
formal parameters. int main()

3. Memory allocated of formal and actual is {


same. So changed made in formals are int x=10;
reflected in actual parameters. add(&x);
Pointer is a variable that stores address of another printf("After function call %d \n", x);
variable. Syntax: *num
In line 4, *num is value at pointer return 0;
x num
}
10 4589 Output: Inside function 20
4589 After function call 20 26
Difference: Call By Value Vs Call By Reference
1. In call by value, the values of the function arguments are passed during
function call while in call by reference, the reference/address of the
function arguments are passedduring functioncall.

2. In call by value, changes are made to the local copies of the arguments, while in
call by reference, changes are made at the addressvalues.

3. In call by value, old values are retained. In call by reference, old values are
updated with newvalues.

4. In call by value, changes are temporary but in call by reference, changes made
are permanent. C by Dr. Deepika Bhatia 27
Example of Call by Reference: WAP to change value 20 to 30

C by Dr. Deepika Bhatia 28


Swapping 2 Numbers- By Call By Value&Call By Reference
// WAP for Call By Value
void swap(int x, int y); // WAP for Call By Reference in C
int main() void swap (int *, int *);
{ int main()
int a = 10, b = 20; {
swap(a, b); //actual paramtr. int a = 10, b = 20;
printf (“a = %d b = %d\n”, a, b); swap (&a, &b);
return 0; printf (“a = %d b = %d\n”, a, b);
} return 0;
void swap(int x, int y) //formal,local }
{ void swap(int *x, int *y)
int t; {
t = x; int t;
x = y; t = *x;
y = t; *x = *y;
printf (“x = %d y = %d\n”, x, y); *y = t;
} }
The output of the program: The output of the above program is:
x = 20 y = 10 a = 20 b = 10
a = 10 b = 20 C by Dr. Deepika Bhatia 29
Question

Q Write a function that receives marks of 3 subject andreturns


average and percentage of these marks

C by Dr. Deepika Bhatia 30


END

C by Dr. Deepika Bhatia 31

You might also like