Sei sulla pagina 1di 32

1

Functions:-

Topics:-

 Definition of a function
 Types of functions
 Uses of functions
 Elements or parts or properties of user defined functions
 Categories of functions or Types of function definitions or Function designs
 Function examples
 Parameter passing mechanisms
 Passing arrays as function parameters
 Recursion
 Storage Classes

Definition:- Function can be defined as a collection of statements that performs the given
task.

Types of functions:- Functions are classified into 2 types.

1. Library functions or Predefined functions or Built in functions


2. User defined functions

1. Library functions or Predefined functions or Built in functions:- These functions are


already defined in the corresponding header file.

Function header file

printf( ) stdio.h

scanf( ) stdio.h

clrscr( ) conio.h

getch( ) conio.h

pow( ) math.h

sqrt( ) math.h

strlen( ) string.h

strcpy( ) string.h

strcat( ) string.h

strrev( ) string.h

strcmp( ) string.h

strlwr( ) string.h

strupr( ) string.h
2

2.User defined functions:- The functions which are defined by the user are known as User
defined functions.

Uses of functions:-

1. Functions are mainly useful for reusability. Reusability means writing the code only
once and using that code many times.
2. Functions eliminate the redundancy (duplication) in the program.
3. Function reduces the size of a program.
4. Functions maintain modular structure of a program.

Elements or parts or properties of user defined functions:-

Any user defined function has 3 parts.

1. Function declaration or Function prototype


2. Function call
3. Function prototype

1.Function declaration or Function prototype:-Like variables functions must be declared


before they are called.

Function prototype contains 4 parts.

1. return_type

2. function_name

3. argument_list or parameter_list

4. Terminating Semicolon

Syntax to declare a function or function prototype:-

return_type function_name(argmument list or parameter list);

return_type:-

 It specifies the data type of the value the function returns.


 If function returns integer value then return type is int.
 The default return type is int i.e. if we didn’t specify any return type then int will be
considered as default return type.
 If the function doesn’t returns any value then return type is void.

function_name:- Identifier rules are to be followed for function_name.

argument_list or parameter_list:- It contains variables along with corresponding data


types. Multiple parameters are seperated bt comma’s.

Terminating semicolon:- Function declaration must ends with semicolon.

Ex:- int add(int a,int b);


3

return fun..name data type of


type the arguments

2.Function call:-
 A function can be called using the function name followed by a list of parameters
separated by comma’s enclosed in parenthesis.
 The arguments passed at function invocation or call is known as actual arguments.

Syntax:- fuction_name(par1,par2,------,parn);

ex:-
c=add(a,b);
Actual arguments
The returning value of add() is assigned to variable c.

 Whenever a function is called then compiler checks whether return type, function
name, number of arguments and order of arguments are same in both function
declaration and function definition or not.
 If there is a mismatch then complier displays type mismatch error.
 If they are same then control will be transferred to the function definition (called
function).
 Once function definition is executed then control will be transferred to the calling
function.

3.Funtion definition:-
 It contains a set of statements which performs the given task.
 It means defining the user defined function.
Syntax:-
return_type function_name(arg1,arg2,. . .)
{

body of function

}
ex:-
int add(int x,int y)
{
int z; Formal arguments
z=x+y;
return(z);
}
Copy of the variables a, b is taken in x and y
z is the local variable used within the function.

The returning value is returned with return statement

return statement:- It returns a single value from called function to calling function.
Syntax:- return variable;
4

Ex:- return a;

Calling function, Called function, actual parameters and formal parameters:-

A function which is calling another function is known as calling function and the parameters
which are used in calling function are known as actual parameters.

A function which is called is known as called function and the parameters which are used in
called function are known as formal parameters.

Ex:- main( )----------calling function

add(a,b); /* here a,b are known as actual parameters because they are used in calling
function*/

add(int x,int y) ) /* here x,y are known as formal parameters because they are used in
called function*/

Categories of functions or Types of function definitions or Function designs:-

Based on the arguments (parameters) and return value user defined functions are defined
using 4 categories.

1. Function with arguments and a return value


2. Function with arguments and no return value
3. Function without arguments and a return value
4. Function without arguments and no return value

1. Function with arguments and a return value:-

 In this category of functions reading should be done in calling function. So called


function receives input from calling function.
 In this category of functions displaying should be done in calling function. So Called
function returns the result to the calling function.

Ex:-

#include<stdio.h>

int sum(int,int);

int main()

{
5

int a,b,res;

printf("\nEnter 2 numbers\n");

scanf("%d%d",&a,&b);

res=sum(a,b);

printf("\nSum=%d",res);

return 0;

int sum(int x,int y)

return (x+y);

Result:-

Input:- Enter 2 numbers 10 20

Output:- sum=30

2. Function with arguments and no return value:-

 In this category of functions reading should be done in calling function. So called


function receives input from calling function.
 In this category of functions displaying should be done in called function. So Called
function doesn’t return any result to the calling function.

Ex:-

#include<stdio.h>

void add(int,int);

int main()

int a,b,res;

printf("\nEnter 2 numbers\n");

scanf("%d%d",&a,&b);

add(a,b);

return 0;

}
6

void add(int x,int y)

int res;

res=x+y;

printf("\nSum=%d",res);

3. Function without arguments and a return value:-

 In this category of functions reading should be done in called function. So called


function doesn’t receives any input from calling function.
 In this category of functions displaying should be done in calling function. So Called
function returns the result to the calling function.

Ex:-

#include<stdio.h>

int add();

int main()

int res;

res=add();

printf("\nSum=%d",res);

return 0;

int add()

int a,b;

printf("\nEnter 2 numbers\n");

scanf("%d%d",&a,&b);

return (a+b);

4. Function without arguments and no return value:-


7

 In this category of functions reading should be done in called function. So called


function doesn’t receives any input from calling function.
 In this category of functions displaying should be done in called function. So Called
function doesn’t return any result to the calling function.

Ex:-

#include<stdio.h>

void add();

int main()

int res;

add();

return 0;

void add()

int a,b;

printf("\nEnter 2 numbers\n");

scanf("%d%d",&a,&b);

printf("\nSum=%d",a+b);

Function Examples:-

Ex1:-Write a C Program using functions that performs arithmetic operations on 2


integers.

An Example for Function definition with arguments and return value.

#include<stdio.h>

#include<conio.h>

int add(int,int);

int sub(int,int);

int mul(int,int);

int div(int,int);
8

int mod(int,int);

int main()

int a,b;

printf("\nEnter 2 numbers");

scanf("%d%d",&a,&b);

printf("\nAddition=%d",add(a,b));

printf("\nSubtraction=%d",sub(a,b));

printf("\nMultiplication=%d",mul(a,b));

printf("\nDivision=%d",div(a,b));

printf("\nModulo=%d",mod(a,b));

return 0;

int add(int x,int y)

return (x+y);

int sub(int x,int y)

return (x-y);

int mul(int x,int y)

return (x*y);

int div(int x,int y)

return (x/y);

}
9

int mod(int x,int y)

return (x%y);

Result:-

Input:- Enter 2 numbers 20 5

Output:-

Addition=25

Subtraction=15

Multiplication=100

Division=4

Modulo=0

Ex2:-Write a C program to compute the cubes of all numbers from 1 to n using


functions.

An Example for Function definition with arguments and no return value.

#include<stdio.h>

void cube(int);

int main()

int n;

printf("\nEnter n");

scanf("%d",&n);

cube(n);

return 0;

void cube(int n)

int i;
10

for(i=1;i<=n;i++)

printf("\nCube of %d is %d",i,i*i*i);

Result:-

Input:-Enter n 5

Output:-

Cube of 1 is 1

Cube of 2 is 8

Cube of 3 is 27

Cube of 4 is 64

Cube of 5 is 125

Ex3:-Write a C program to print biggest of 3 numbers using functions.

An Example for Function definition without arguments and return value.

#include<stdio.h>

int big();

int main()

int res;

res=big();

printf("\nBigeest number is %d",res);

return 0;

int big()

int x,y,z;

printf("\nEnter 3 numbers");
11

scanf("%d%d%d",&x,&y,&z);

if(x>y && x>z)

return x;

else if(y>z)

return y;

else

return z;

Result:-

Input:- Enter 3 numbers 11 33 22

Output:-Biggest number is 33

Ex4:-Write a C program to check the number is Armstrong or not using functions.

An Example for Function definition without arguments and no return value.

#include<stdio.h>

void armstrong();

int main()

armstrong();

return 0;

void armstrong()

int n,r,sum=0,temp;

printf("\nEnter a value");

scanf("%d",&n);

temp=n;

while(n!=0)

{
12

r=n%10;

sum=sum+r*r*r;

n=n/10;

if(sum==temp)

printf("\nArmstrong number");

else

printf("\nNot an armstrong number");

Result:-

Input:- Enter a value 153

Output:-Armstrong number

Ex5:-Write a C program to print factorial of a number using functions (Iteration).

TYPE 1:An Example for Function definition with arguments and return value.

#include<stdio.h>

int fact(int);

int main()

int n,res;

printf("\nEnter n value");

scanf("%d",&n);

res=fact(n);

printf("\nFactorial value is %d",res);

return 0;

int fact(int n)

int i,f=1;
13

for(i=1;i<=n;i++)

f=f*i;

return f;

TYPE 2:An Example for Function definition with arguments and no return value.

#include<stdio.h>

void fact(int);

int main()

int n,res;

printf("\nEnter n value");

scanf("%d",&n);

fact(n);

return 0;

void fact(int n)

int i,f=1;

for(i=1;i<=n;i++)

f=f*i;

printf("\nFactorial value is %d",f);

TYPE 3:An Example for Function definition without arguments and return value.

#include<stdio.h>

int fact();

int main()

int res;

res=fact();
14

printf("\nfactorial value is %d",res);

return 0;

int fact()

int i,n,f=1;

printf("\nEnter n value");

scanf("%d",&n);

for(i=1;i<=n;i++)

f=f*i;

return f;

TYPE 4:An Example for Function definition without arguments and no return value.

#include<stdio.h>

void fact();

int main()

fact();

return 0;

void fact()

int i,n,f=1;

printf("\nEnter n value");

scanf("%d",&n);

for(i=1;i<=n;i++)

f=f*i;

printf("\nFactorial value is %d",f);

}
15

Parameter passing techniques(mechanisms):- To pass the parameters or arguments from


calling function to called function 2 techniques are used.

1.Call by value or pass by value

2.Call by address or call by reference or pass by address or pass by reference

1.Call by value:-

 The method of passing arguments by value is called call by value.


 In call by value the values of actual arguments are passed to the formal arguments.
 So actual arguments and formal arguments will be created at different memory
locations.
 In call by value the changes made to the formal arguments of called function will not
be reflected on actual arguments of calling function.
 So call by value means the values of actual arguments will not be changes even if they
are modified in called function.

C program to swap 2 numbers using call by value mechanism:-

#include<stdio.h>

void swap(int,int);

int main()

int a,b;

printf("\nEnter 2 numbers");

scanf("%d%d",&a,&b);

printf("\nBefore function call a value is %d and b value is %d",a,b);

swap(a,b);

printf("\nAfter function call a value is %d and b value is %d",a,b);

return 0;

void swap(int a,int b)

int temp;

temp=a;

a=b;

b=temp;
16

Result:-

Input:- Enter 2 numbers 11 22

Output:-

Before function call a value is 11 and b value is 22

After function call a value is 11 and b value is 22

2.Call by address:-

 The method of passing arguments by address is called call by address.


 In call by address the addresses of actual arguments are passed to the formal
arguments.
 So actual arguments and formal arguments will shares the same memory location.
 In call by address the changes made to the formal arguments of called function will be
reflected on actual arguments of calling function.
 So call by address means the values of actual arguments will be changes if they are
modified in called function.

C program to swap 2 numbers using call by reference mechanism:-

#include<stdio.h>

void swap(int *,int *);

int main()

int a,b;

printf("\nEnter 2 numbers");

scanf("%d%d",&a,&b);

printf("\nBefore function call a value is %d and b value is %d",a,b);

swap(&a,&b);

printf("\nAfter function call a value is %d and b value is %d",a,b);

return 0;

void swap(int *a,int *b)

{
17

int temp;

temp=*a;

*a=*b;

*b=temp;

Result:-

Input:- Enter 2 numbers 11 22

Output:-

Before function call a value is 11 and b value is 22

After function call a value is 22 and b value is 11

Functions with arrays or Passing arrays as function arguments:-

Like normal variables we can also pass arrays as arguments to the function.

While passing arrays as arguments to the function, only the name of the array is passed ( i.e.
starting address of area is passed as argument).

Function call:- sum(a);

Function declaration:-- return type fun_name(data_type []);

Ex:- int sum(int []);

Function definition:- int sum(int a[])

Function body

Ex1:- Write a c program to find the sum and average of array elements using functions.

#include<stdio.h>

#include<conio.h>

int sum(int [],int);

float avg(int [],int);

int s;

main()

{
18

int res,i,n,a[10];

clrscr();

printf("\nenter size of array\n");

scanf("%d",&n);

printf("\nenter array elements\n");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

printf("\nSum=%d",sum(a,n));

printf("\nAverage=%f",avg(a,n));

getch();

int sum(int a[],int n)

int i;

for(i=0;i<n;i++)

s=s+a[i];

return s;

float avg(int a[],int n)

float average;

int i,s=0;

for(i=0;i<n;i++)

s=s+a[i];

average=(float)s/n;

return average;

Ex2:- c program to sort the array using functions

#include<stdio.h>
19

void sort(int [],int);

int main()

int i,n,a[10];

printf("\nenter size of the array");

scanf("%d",&n);

printf("\nenter elements of the array");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

sort(a,n);

printf("\nAfter sorting elements of array are:\n");

for(i=0;i<n;i++)

printf("%d\t",a[i]);

return 0;

void sort(int a[],int n)

int i,j,temp;

for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
20

Recursion:- A function which is called by itself is known as recursion i.e. calling function
and called function should be same.

Ex1:-Write a function to return G.C.D of 2 numbers using recursion.

#include<stdio.h>

int gcd(int,int);

int main()

int a,b,res;

printf("\nEnter 2 numbers");

scanf("%d%d",&a,&b);

res=gcd(a,b);

printf("\nGCD of a and b is %d",res);

return 0;

int gcd(int a,int b)

if(a==0)

return b;

else if(b==0)

return a;

else

gcd(b,a%b);

Result:-

Input:- Enter 2 numbers 16 20

Output:- GCD of a and b is 4

Ex2:-Write a c program to find the factorial of a given number using recursion.

#include<stdio.h>
21

int fact(int);

int main()

int n,res;

printf("\nEnter a number");

scanf("%d",&n);

res=fact(n);
printf("\nfactorial value is %d",res);
return 0;
}
int fact(int n)
{
if(n==0)
return 1;
else
return n*fact(n-1);
}
Result:-
Input:- Enter a number 5
Output:- factorial value is 120
Ex3:-Write a c program to return the power of a given number using recursion.
#include<stdio.h>
int power(int,int);
int main()
{
int base,expo,res;
printf("\nEnter base and exponent values\n");
scanf("%d%d",&base,&expo);
res=power(base,expo);
printf("\nResult is %d",res);
return 0;
22

}
int power(int base,int expo)
{
if(expo==0)
return 1;
else
return base*power(base,expo-1);
}
Ex4:-Write a c program to solve the towers of hanoi problem of 3 disks using recursion.
It is a classical recursion problem. In this the disks are moved from source tower to
destination tower using the following rules.
Rule 1:- Only one disk can be moved at a time.
Rule 2:- Larger disk can’t be placed on the top of smaller disk.
Rule 3:- Auxiliary tower can be used for temporary storage of disks.
Program:-
#include<conio.h>
void hanoi(int,char,char,char);
main()
{
int n;
char src='S',aux='A',dest='D';
clrscr();
printf("enter no of disks");
scanf("%d",&n);
hanoi(n,src,aux,dest);
getch();
}
void hanoi(int n,char src,char aux,char dest)
{
if(n==1)
printf("\nMove disk from %c to %c",src,dest);
23

else
{
hanoi(n-1,src,dest,aux);
hanoi(1,src,aux,dest);
hanoi(n-1,aux,src,dest);
}
}
Result:-
Input:- enter no of disks 3
OutPut:-
Move disk from S to D
Move disk from S to A
Move disk from D to A
Move disk from S to D
Move disk from A to S
Move disk from A to D
Move disk from S to D

Example:- Refer next page


24
25
26

Storage Classes Or Scope rules of a variable

Storage class of a variable provides the following information.

1. Storage area:- It specifies where the variable is stored .Generally a variable is stored
either in memory or CPU registers.
2. Default initial value:-It specifies default initial value of a variable if the initial value
is not specified.
3. Scope of a variable:- It is the region or area in which the variable can be used.
Generally the scope may be within the function, block or program.
4. Life time of a variable:- It specifies how long the value of variable is available in
program execution.

Types of Storage classes:- Storage classes are classified into 4 types.

1. auto storage class


2. static storage class
3. extern storage class
4. register storage class

1.auto storage class:-

These variables are known as local variables or automatic variables. These variables are
declared inside a function or block.

Syntax to declare a variable:- storage_class data_type variable;

Ex:- auto int a;

auto storage class of a variable provides the following information.

1. Storage area:- Local variables are stored in memory.


2. Default initial value:- The default initial value of local variable is garbage
value(unpredictable value).
3. Scope of a variable:- The scope of local variable is a function or block in which the
variable is declared.
4. Life time of a variable:- The value of local variable is available as long as the control
remains in the function or block.

Ex1:-

#include<stdio.h>

void incr();

int main()

incr();

incr();

incr();
27

return 0;

void incr()

auto int a=0;

printf("\na=%d",a);

a++;

Ouput:-

a=0

a=0

a=0

Ex2:-

#include<stdio.h>

int main()

auto int x;

printf("\nx=%d",x);

x=10;

auto int x=20;

printf("\nInside block x=%d",x);

printf("\nOutside block x=%d",x);

return 0;

Output:-

x=58 (garbage value)

Inside block x=20


28

Outside block x=10

2.static storage class:-

These variables are known as static variables. These variables are declared inside a function
or a block.

Syntax to declare a variable:- storage_class data_type variable;

Ex:- static int a;

static storage class of a variable provides the following information.

1. Storage area:- static variables are stored in memory.


2. Default initial value:- The default initial value of static variable is zero.
3. Scope of a variable:- The scope of static variable is a function or a block in which
the variable is declared.
4. Life time of a variable:- The value of static variable is available between different
function calls.

Ex:-

include<stdio.h>

void incr()

static int a;

printf("\na=%d",a);

a++;

int main()

incr();

incr();

incr();

return 0;

Output:-

a=0

a=1
29

a=2

3.extern storage class:-

These variables are known as extern variables or global variables. These variables are
declared before or after the main( ).

Syntax to declare a variable:- storage_class data_type variable;

Ex:- extern int a;

If a variable is declared before main( ) then it is by default a global variable.

static storage class of a variable provides the following information.

1. Storage area:- global variables are stored in memory.


2. Default initial value:- The default initial value of global variable is zero.
3. Scope of a variable:- The scope of global variable is throughout the program.
4. Life time of a variable:- The value of global variable is available as long as the
control remains in the program

Ex:-

#include<stdio.h>

void incr();

void decr();

extern int a=10;

int main()

printf("\nIn main() a value is %d",a);

incr();

decr();

return 0;

void incr()

a=a+20;

printf("\nIn incr() a value is %d",a);

}
30

void decr()

a=a-10;

printf("\nIn decr() a value is %d",a);

Output:-

In main() a value is 10

In incr() a value is 30

nIn decr() a value is 20

4.register storage class:-

These variables are known as register variables. These variables are declared inside a
function or block.

Syntax to declare a variable:- storage_class data_type variable;

Ex:- register int a;

register storage class of a variable provides the following information.

1. Storage area:- register variables are stored in CPU registers.


2. Default initial value:- The default initial value of register variable is garbage
value(unpredictable value).
3. Scope of a variable:- The scope of register variable is a function or block in which
the variable is declared.
4. Life time of a variable:- The value of register variable is available as long as the
control remains in the function or block.

Ex:-

#include<stdio.h>

int main()

register int i;

for(i=1;i<=100;i++)

printf("\ni=%d",i);

return 0;

Output:-
31

i=1

i=2

---

---

i=100

C Program to demonstrate all the storage classes:-

#include<stdio.h>

void incr();

int a=5;

int main()

int x;

printf("\nx=%d",x);

x=10;

int x=15;

printf("\nx=%d",x);

incr();

incr();

printf("\nx=%d",x);

return 0;

void incr()

static int b;

printf("\na=%d",a);

printf("\nb=%d",b);

a++;
32

b++;

Output:-

x=garbage value

x=15

a=5

b=0

a=6

b=1

x=10

Potrebbero piacerti anche