You are on page 1of 42

Chapter -5 Function

 Topics:-

• Concept of user defines functions


• Definition of Function
• Parameter & Parameter Passing
• Calling a function
• Recursive function
• Macros
 What is Function ?
• A Function is a name, self-contained block of statements that perform a
specific task and may return a value to the program.
 Advantages of Functions :
1. It represents a small & specific  task
 Which makes program easier to understand , implement
and maintain.

2. It reduce length of program and thus saves Memory.


 The function is written once in a program, but used many times which
reduces the length of the program and saves the MEMORY.

3. It increase reusability and reliability of program.


 Function written in one program can be used also in other program.
This increase not only the reusability of program but also increase
reliability as function is already tested when developed first time.

4. Dividing a program in to functions brings the preciseness in to design.


 It make program more understable.
 Types of functions in C

FUNCTION
S

PRE- USER-
DEFINED DEFINED

 User defined functions are written by the user and the user has the
freedom to choose the function name, number and types of arguments
and he will decide whether the function should return any value or not.
1. Predefined Functions(Library Functions)
Examples:

 Printf()
 Scanf()
 Getchar()
 Sin()
 Sqrt()
 Pow()
2. User defined Functions
 Example

#include<stdio.h>
int add(int,int); // Function Declaration
void main()
Caller
{ Actual Argument
Function int a=3,b=4,c;
c = add(a,b); // Function Call
printf(“c=%d”,c); Formal/Dummy Argument
}
int add(int p,int q)
{
Called
Function int n;
n=p +q; Function Defination
return(n);
}
 Example
 Example
 Categories of Functions
• Depending upon number of arguments receives and the type of value it
returns.

 Categories of Function

1. Function with no arguments and no return values


2. Function with arguments but no return values
3. Function with arguments and one return values
4. Function with no arguments but return values
5. Function that returns multiple values
1. Function with no arguments and no return
values
2. Function with arguments but no return values
3. Function with arguments and one return values
4. Function with no arguments but return values
 Parameter Passing
 There are two ways to pass arguments(data or value) to a function.
i) Pass argument by value(call by value).
ii) Pass arguments by address or by pointer(call by reference)

• Original value is not modified in call by value but it is modified in call by


reference.
1. Call by Value
• The contents of the actual parameters get copied into the corresponding
formal parameters.
• In call by value, original value is not modified.
• In call by value, value being passed to the function is locally stored by the
function parameter in stack memory location. If you change the value of
function parameter, it is changed for the current function only. It will not
change the value of variable inside the caller method such as main().
• Let's try to understand the concept of call by value in c language by
the example given below:

#include <stdio.h>  
#include <conio.h>  
void change(int num) {  
    printf("Before adding value inside function num=%d \n",num);
    num=num+100;  
    printf("After adding value inside function num=%d \n", num);  
}  
  
int main() {  
    int x=100;  
    clrscr();  
    printf("Before function call x=%d \n", x);  
    change(x);//passing value in function  
    printf("After function call x=%d \n", x);  
    getch();  
    return 0;  
}  
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
 W.A.P to swapping of two variable value using call by
value
#include<stdio.h>
void swapval(int , int);
void main()
{
int x,y;
printf(“enter two value”);
scanf(“%d %d”,&x,&y);
5 20
swapval(x,y); x y
getch();
}
void swapval(int a, int b) a b
5 20
{
int temp;
temp=a;
a=b;
b=temp;
printf(“%d %d”,a,b);
}
2. Call by reference
 In this method, the contents of the arguments in the calling function get
changed.

 Instead of passing the value of a variable, we can pass the memory address of
the variable to the function. This is called as call by reference.

Here, address of the value is passed in the function, so actual and formal
arguments shares the same address space. Hence, value changed inside the
function, is reflected inside as well as outside the function.
• Let's try to understand the concept of call by reference in c language by the
example given below:

#include <stdio.h>
#include <conio.h>
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
}
int main() {
int x=100;
clrscr();
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
getch();
return 0;
}
Output:
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
 W.A.P. to swapping of two variable value using call by
reference
#include<stdio.h>
void swapref(int int);
void main()
{
&x &y
intx,y 1000 1002
printf(“enter two number”);
scanf(“%d %d”,&x,&y);
swapref(&x,&y);
}
void swapref(int *a, int *b)
*a *b
{ 10 20
int temp;
temp=a;
a=b;
b=temp;
printf(“%d %d”,a,b);
}
 Difference between call by value and call by
reference in c
Call by value Call by reference
(1) A copy of value is passed to the (1) An address of value is passed to
function the function

(2) Changes made inside the (2) Changes made inside the
function is not reflected on other function is reflected outside the
functions function also.
(3) Actual and formal arguments (3) Actual and formal arguments
will be created in different memory will be created in same memory
location. location
  Scope of Variable
• The part of program within which a variable can be accessed, is
called it’s SCOPE.

SCOPE

GLOBA
LOCAL
L
1. LOCAL

• By default the scope of variable is local to the function in which it is


defined.
• Local variables can access in that function in which they are defined.
• Unknown to other function in same program.
• Also known as Internal variables.

2. Global
• If a variable is defined outside the function than it can be access by whole
program.
• Variables which are declared out side the function are also known as
External variables.
  Difference between Local and Global variables

LOCAL VARIABLES GLOBAL VARIABLES


(1) Accessible inside a (1) Accessible during
function that creates them. execution of whole program
(2) Have allocated memory on (2) Have allocated memory on
stack. Data Segment
(3) Are not initialized (3) Are normally initialized to
automatically 0 by default.
  Lifetime of Variable

• Variables life time is a period of time during which the variable


exist during execution(remain in memory).

• There are three life times of variables.

LIFE TIME

AUTOMATI
STATIC DYNAMIC
C
1. Dynamic
• The memory allocation by the call of malloc is called dynamic

2. Automatic
• Automatic variable’s memory location is created when the block in
which it is declared is entered.
• These variables are exist while the block is active, and then it is
destroyed when the block is exited.
• Local variable is an automatic variable.

3. Static
• The static variable is a variable that exist from the point at which the
program begins execution and continue to exist during duration of the
program.
• storage of static variable is allocated and initialized once when the
execution begins.
• Same as global variables
  Explanation of life and scope of variable

#include<stdio.h> LIFE ACCESS


Int a=7 //global
void main()
{
int b=3; //local to main a/b a/b
abc();
…………... a/b a/b
xyz(); a/b a/b
}
abc()
{
int c=4; // local to abc()
} a/b/c a/c
xyz()
{
int d=9; //local to xyz(); a/b/d a/d
}
  Recursion
• Recursion is a process by which function calls it self repeatedly, until
some specified condition has been satisfied.

• Syntax

return type function_name(<argument list>)


{………..
…………
function_name(….);
………….
}
 WAP to find factorial of given number using
recursion
#include<stdio.h>  
#include<conio.h>  
int factorial (int n)  
{  
    if ( n < 0)  
        return -1; /*Wrong value*/  
    if (n == 0)  
        return 1; /*Terminating condition*/  
    return (n * factorial (n -1));  
}  
  
void main(){  
int fact=0;  
clrscr();  
fact=factorial(5);  
printf("\n factorial of 5 is %d",fact);  
  
getch();  
}  
Output:

factorial of 5 is 120
 Advantages of Recursion :
1. It solve problem in easier way than using iterative loops

 Ex. tower of honoi

2. It reduce Size of code.

3. Complex program can be easily written using recursion.


 Disadvantage of Recursion :
1. To many recursive function may cause confusion in the code.
2. Recursive solution is logical and it is difficult to debug and
understand.
3. It makes program execution slower.
4. In recursive function if statement is compulsory to return outside
from the function. otherwise it executes infinite times.
 Macro Function
• In C macro can be defined using #define .
• A simple example of a macro function with arguments is :
Write a function program to add first N numbers
#include <stdio.h>
#include <conio.h>
int add(int x)
{
inti,sum=0;
for(i=1;i<=x;i++)
{
sum=sum+i;
}
}
void main ()
{
int i, j,n,k;
clrscr();
printf("enter the number:");
scanf("%d",&n);
k = add(n);
printf ("The value of k is:%d", k);
getch();
}

OUTPUT:
enter the number:10
The value of k is:55
Write a function find out maximum out of three numbers
#include<stdio.h>
void main()
#include<conio.h>
{
intx,y,z;
int largest(inta,intb,int c)
clrscr();
{
largest(x,y,z);
printf("Enter three numbers: ");
getch();
scanf("%d %d %d", &a, &b, &c);
}
if(a>=b && a>=c)
{
OUTPUT:
printf("Largest number = %2d", a);
Enter three numbers: 23 45 12
}
Largest number = 45
else if(b>=a && b>=c)
{
printf("Largest number = %2d", b);
}
else
{
printf("Largest number = %2d", c);
}
}
Write a function prime that return 1 if it‘s argument is
prime and return 0 otherwise.
#include<stdio.h>
int prime(int n)
#include<conio.h>
{
int prime(int);
if(n%i==0)
void main()
{
{
return 0;
intn,p;
}
clrscr();
else
printf("Enter a number : ");
{
scanf("%d",&n);
return 1;
p=prime(n);
}
if(p==1)
{
}
printf("%d is prime\n",n);
Output:
}
Enter a number : 18
else
18 is not prime
{
Enter a number : 5
printf("%d is not
5 is prime
prime\n",n);
}
getch();
}
Write a calculator program(add,subtract,multiply,divide).
Prepare user defined function for each functionality
#include<stdio.h> void add(int a,int b)
#include<conio.h> {
int c;
c=a+b;
void add(inta,int b);
printf("\nAddition =%d",c);
void sub(inta,int b); }
void mul(inta,int b); void sub(int a,int b)
void div(inta,int b); {
void main() int c;
{ c=a-b;
intx,y; printf("\nSubstration =%d",c);
clrscr(); }
void mul(int a,int b)
printf("enter the value:");
{
scanf("%d %d",&x,&y); int c;
add(x,y); c=a*b;
sub(x,y); printf("\nMultiplication =%d",c);
mul(x,y); }
div(x,y); void div(int a,int b)
getch(); { int c;
} c=a/b;
printf("\nDivision =%d",c);

}
Thank You…

You might also like