0% found this document useful (0 votes)
6 views

Function

The document provides an overview of functions in C programming, detailing their types, declaration, definition, and calling mechanisms. It explains standard library functions, user-defined functions, and various function categories, including parameter passing techniques like call by value and call by reference. Additionally, it covers recursion, illustrating how functions can call themselves and the flow of control in recursive calls.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Function

The document provides an overview of functions in C programming, detailing their types, declaration, definition, and calling mechanisms. It explains standard library functions, user-defined functions, and various function categories, including parameter passing techniques like call by value and call by reference. Additionally, it covers recursion, illustrating how functions can call themselves and the flow of control in recursive calls.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Function

A function is a block of code that performs a specific task. Every C program has at
least one function, which is main(), and all the most trivial programs can define
additional functions.
Types of function
1. Standard library function
2. User defined function

1. Standard Library Function


These functions are present in c library and they are predefined.
Ex.: scanf(), printf(), sqrt(), strlen() etc.

To use the above library function we have to include corresponding header file using
pre-processor directive i.e #include.

2.User defined Function

A function that is declare, calling and define by the user is called user define
function. Here logic is provided by user. Every user define function has three parts
as:

1. Function Prototype or Declaration


2. Function Calling
3. Function Definition

For writing a function name , the rules are same as the rules for writing a variable
name.

User defined function is always written outside the main function i.e above the main
function or below the main function, but to use that function we have to give
reference of that function in the main function. Giving reference is called function
call.

Each function is having its own functionalities . To use one function someone has to
call it. Ex.TV has different functionalities. Remote has also different functionalities,
but they do not work on their own. We use them by pressing keys. So without
function call we can’t use its functionalities.

Example:
#include<stdio.h>
int sum(int,int); //Function declaration
void main()
{
int a=10,b=20,s;
s=sum(a,b); // Function Call
printf(“sum is %d”,s);
}
int sum(intx,int y) // Function Defination
{
returnx+y;
}

Function Declaration/ Function prototype

It informs the computer about the three things


a) Name of the function
b) Number and type of arguments received by the function.
c) Type of value return by the function
It does not contain function body.

Calling function need information about called function .If called function is place
before calling function then the declaration is not needed. The argument list in the
function definition as well as function declaration must be matched.

Syntax :
return_typefunction_name (type1 arg1 , type2 arg2);
OR
return_typefunction_name (type1, type2);

Function Call
A function is called by simply writing its name followed by the argument list inside the
parenthesis.

Syntax:
function_name(arg1,arg2..);

Example:
void main() //Calling function
{
x();
printf(“Hello”);
y();
}
x() //Called function
{
printf(“welcome”);
}
y()
{
printf(“How are you”);
}
Output:
Welcome
Hello
How are you
Note: A function can be called from other function but a function can’t be defined in
another function.

Function Definition

1. It consists of code description and code of a function .


It consists of two parts
a) Function header
b) Function coding
Function definition tells what are the I/O function and what is going to do.
Syntax:
return_typefunction_name (type1 arg1 , type2 arg2)
{
local variable; statements ; return (expression);
}
2. Function definition can be placed any where in the program but generally placed
after the main function .

3. Local variable declared inside the function is local to that function. It cannot be
used anywhere in the program and its existence is only within the function. Function
declaration outside the main function is called global declaration. Such a function
can be be accessed by all function in program. Function declaration inside the main
function is called local declaration and it is accessed by only main().

4. Function definition cannot be nested.

5. Return type denote the type of value that function will return and return type is
optional if omitted it is assumed to be integer by default.

In C we can do both declaration and definition at same place and at that time no
semicolon is used,

Calling function is the function which is having function call statement.

The function which we call / use is called called function.


Actual Arguments:
1. Arguments which are mentioned in the function call are known as actual
parameters.
2. These are the values which are actual arguments called to the function.

It can be written as constant , function expression on any function call which return a
value .
ex: funct (6,9) , funct ( a,b )

Formal Arguments:

1. Arguments which are mentioned in function definition are called dummy or formal
argument.
2. These arguments are used to just hold the value that is sent by calling function.
3. Formal arguments are like other local variables of the function which are created
when function call starts and destroyed when end function.

Basic difference between formal and local argument are:


a) Formal arguments are declared within the ( ) where as local variables are
declared at beginning.

b) Formal arguments are automatically initialized when a value of actual argument is


passed.

c) Where other local variables are assigned variable through the statement inside the
function body.

Note: Order, number and type of actual argument in the function call should be
matched with the order , number and type of formal arguments in the function
definition .
Function Categories

There are four main categories of the functions these are as follows:

1. Function with no arguments and no return values.


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

Function with no arguments and no return values:


syntax:
voidfunct (void);
main ( )
{
funct ( );
}
voidfunct ( void );
{
}

NOTE: There is no communication between calling and called function. Functions


are executed independently, they read data & print result in same block.

Example:
void link (void) ;
void main ()
{
link ();
}
void link ( void )
{
printf (“ link the file “)
}

Function with no arguments and a return value


This type of functions has no arguments but a return value
example:
intmsg (void) ;
void main ( )
{
int s = msg ( );
printf( “summation = %d” , s);
}
intmsg ( void )
{
int a, b, sum ;
sum = a+b ;
return sum ;
}
NOTE: Here called function is independent, it read the value from the keyboard,
initialize and return a value .Both calling and called function are partly communicated
with each other.

Function with arguments and no return values


Here functions have arguments so, calling function send data to called function but
called function does no return value. such functions are partly dependent on calling
function and result obtained is utilized by called function .
Example:
voidmsg ( int , int );
void main ( )
{
inta,b;
a= 2; b=3;
msg( a, b);
}
voidmsg ( int a , int b)
{
int sum ;
sum = a+b;
printf (“sum = %d” , sum ) ;
}

Function with arguments and return value:


Here calling function of arguments that passed to the called function and called
function return value to calling function.
example:
intmsg ( int , int ) ;
void main ( )
{
int a, b;
a= 2; b=3;
int s = msg (a, b);
printf (“sum = %d” , s ) ;
}
intmsg( int a , int b)
{
int sum ;
sum =a+b ;
return (sum);
}
Parameter Passing Techniques:

1. call by value
2. call by reference

Call by Value method

1. Here the copy of actual arguments is passed to the formal arguments and
operation is done in the formal argument.
2. Since formal arguments are photo copy of actual argument, any change of the
formal arguments does not affect the actual arguments. Memory occupied by
actual arguments and formal arguments are different. So Only changes are made
in the memory location occupied by formal parameters.
3. Changes made to the formal argument t are local to block of called function, so
when control back to calling function changes made vanish.
4. .

Example:
void swap (int a , int b) /* called function */
{
int t;
t = a;
a=b;
b = t;
printf(“value of a & b is %d%d”,a,b);
}
main( )
{
int k = 50,m= 25;
swap( k, m) ; / * calling function */
printf(“after swapping in calling function %d %d”,k,m);
}
Output:
Value of a & b is 25 50
After swapping in calling function 50 25

Explanation:
int k= 50, m=25 ;
Means first two memory space are created k and m , store the values 50 and 25
respectively.
swap (k,m);
When this function is calling the control goes to the called function.
void swap (int a , int b),
k and m values are assigned to the ‘a’ and ‘b’.
then a= 50 and b= 25 ,
After that control enters into the function a temporary memory space ‘t’ is created
when int t is executed.
t=a; Means the value of a is assigned to the t , then t= 50.
a=b; Here value of b is assigned to the a , then a= 25;
b=t; Again t value is assigned to the b , then b= 50;
after this control again enters into the main function and execute the printf(k,m). it
returns the value 50 , 25.

NOTE:
Whatever change made in called function not affects the values in calling function.
Call by reference method

Here instead of passing value address or reference are passed as arguments in


function call. Function operators or address rather than values .Here formal
arguments are the pointers to the actual arguments. A function receives an implicit
reference to the argument rather than a copy of its value. Therefore, the function can
modify the value of variable and that change will be reflected in the calling function.
Both actual and formal parameters share common memory address.

Example:

void swap (int * a , int * b) /* called function */


{
int t;
t =* a;
*a=*b;
*b = t;
printf(“value of a & b is %d%d”,*a,*b);
}
main( )
{
int k = 50,m= 25;
swap(& k,& m) ; / * calling function */
printf(“after swapping in calling function %d %d”,k,m);
}
Output:
Value of a & b is 25 50
After swapping in calling function 25 50

‘&’ symbol is used for getting the address. ‘*’ is used for getting the value from
corresponding address. int * a means value at address of a.
NOTE:
In call by address mechanism whatever change made in called function affect the
values in calling function

Passing array to a function in C

Here you will learn to pass the array (both 1D or multi dimensional arrays) to a
function in C programming with some examples.
Before passing the entire array element, let’s see how you can pass individual
elements of an array to a function.
Passing array elements to a function is similar to passing variables to a function.
Example 1:Passing an array

void display(int a1,int a2)


{

printf(“%d”,a1);
printf(“%d”,a2);
}
void main()
{
intarr[]={5,20,45,33,16};
display(arr[1].arr[4]); //passing 2nd and 5th element to display()
}
Output: 20 16
Example 2: Passing arrays to a function

//Programme to calculate sum of array elements by passing to a function


float sum(float mark[]);
In function declaration only
void main()
the array name/address
{ passed.[ ] mentioned to
indicate an array.
float marks[]={55.5,65.5,78,45.7,98},result;
result=sum(marks); //marks array is passed to sum function (To pass an entire array
to the function, only the name of the array is passed as an argument.)
printf(“Total=%f”,result);
}
float sum(float mark[])
{

inti;
float x=0.0;
for(i=0;i<5;i++)
x=x+mark[i];
return x;
}

Output: Total 342.7


Example 3: Passing 2D arrays

void display(intarr[2][2]);
void main()
{
intarr[2][2],i,j;

printf(“enter 4 numbers\n”);
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf(“%d%d”,&arr[i][j]);
display(arr); //Passing 2D array to the function
}

void display(intarr[2][2])
{
intx,y;
printf(“Displaying:\n”);
for (x=0;x<2;x++)
for(y=0;y<2;y++)
printf(“%d\n”,arr[x][y]);
}
Output: enter 4 numbers:
2
5

7
9
Displaying:
2
5
7

9
NOTE:In C prog.,you can pass arrays to functions, however you can’t return array
from functions.
Example 4: Display a string using function

void display(char a[])


{
printf(“%s”,a);
}
void main()
{

char a[6]=”Hello”;
display(a); //Passing string as an argument to function
}
Output: Hello

Recursion

Recursion is a process in which a problem is defined in terms of itself. In ‘C’ it is


possible to call a function from itself. Functions that call themselves are known as
recursive functions, i.e. a statement within the body of a function calls the same
function. Recursion is often termed as ‘Circular Definition’. Thus recursion is the
process of defining something in terms of itself. To implement recursion technique in
programming, a function should be capable of calling itself.
Advantages:
1. Reduce unnecessary calling of functions
2. Through recursion one can solve problems in a easy way while its iterative
solution is very big and complex.
Example:
void main()
{
Statements

fun();
statements
}
void fun()
{
statements

fun(); /*RECURSIVE CALL*/


statements
}
Here the function fun() is calling itself inside its own function body, so fun() is a
recursive function. When main() calls fun(), the code of fun() will be executed and
since there is a call to fun() inside fun(), again fun() will be executed. It looks like the
above program will run up to infinite times but generally a terminating condition is
written inside the recursive functions which end this recursion.
The following program (which is used to print all the numbers starting from the given
number to 1 with successive decrement by 1) illustrates this:

void main()
{
int a;
printf(“Enter a number”);
scanf(“%d”,&a);
fun(a);
}
int fun(int b)
{
printf(“%d”,b);
b--;
if(b>=1) /* Termination condition i.e. b is less than 1*/
{
fun(b);
}
}
How control flows in successive recursive calls?
Flow of control in successive recursive calls can be demonstrated in following
example:
Consider the following program which uses recursive function to compute the
factorial of a number.

int fact(int);
void main()

{
intn,f;
printf(“Enter a number”);
scanf(“%d”,&n);
f=fact(n);
printf(“Factorial of %d is %d”,n,f);
}
int fact(int m)
{
int a;
if (m==1)
return 1;
else
a=m*fact(m-1);
return a;
}

In the above program if the value entered by the user is 1 i.e.n=1, then the value of n
is copied into m. Since the value of m is 1 the condition ‘if (m==1)’ is satisfied and
hence 1 is returned through return statement i.e. factorial of 1 is 1.

When the number entered is 2 i.e. n=2, the value of n is copied into m. Then in
function fact(), the condition ‘if(m==1)’ fails so we encounter the statement
a=m*fact(m-1); and here we meet rcursion. Since the value of m is 2 the expression
(m*fact(m-1)) is evaluated to (2*fact(1)) and the result is stored in a(factorial of a).
Since value returned by fact(1) is 1 so the above expression reduced to (2*1) or
simply 2. Thus the expression m*fact(m-1) is evaluated to 2 and stored in a and
returned to main(). Where it will print ‘Factorial of 2 is 2’.

In the above program if n=4 then main() will call fact(4) and fact(4) will send back the
computed value i.e. f to main(). But before sending back to main() fact(4) will call
fact(4-1) i.e. fact(3) and wait for a value to be returned by fact(3). Similarly fact(3) will
call fact(2) and so on. This series of calls continues until m becomes 1 and fact(1) is
called, which returns a value which is so called as termination condition. So we can
now say what happened for n=4 is as follows
fact(4) returns (4*fact(3) )
fact(3) returns (3*fact(2) )
fact(2) returns (2*fact(1) )
fact(1) returns (1)
So for n=4, the factorial of 4 is evaluated to 4*3*2*1=24.
For n=3, the control flow of the program is as follows:

From main()

int fact(int m)//m=3 int fact(int m) //m=2 int fact(int m) //m=1


{ { {
int a; int a; int a;
if(m==1) if(m==1) if(m==1)
return 1; return 1; return 1;
else else else
a=m*fact(m- a=m*fact(m-1); a=m*fact(m-1);
1);//3*fact(2)recursive call //2*fact(1) recursive call return a;
return a; return a;
}//Here it returns 3*2=6 }//Here it returns 2*1=2

To main()

Implementation of Recursion

We came to know that recursive calls execute like normal function calls, so there is
no extra technique to implement recursion. All function calls(Whether Recursive or
Non-Recursive) are implemented through run time stack. Stack is a Last In First
Out(LIFO) data structure. This means that the last item to be stored on the
stack(PUSH Operation) is the first one which will be deleted(POP Operation) from
the stack. Stack stores Activation Record(AR) of function during run time. Here we
will take the example of function fact() in the previous recursive program to find
factorial of a number.
Suppose fact() is called from main() with argument 3 i.e.
fact(3); /*From main()*/

Now will see how the run time stack changes during the evaluation of factorial of 3.
The following steps will reveal how the above stack contents were expressed:
First main() is called, so PUSH AR of main() into the stack. Then main() calls fact(3)
so PUSH AR of fact(3). Now fact(3) calls fact(2) so PUSH AR of fact(2) into the
stack. Likewise PUSH AR of fact(1). After the above when fact(1) is completed, POP
AR of fact(1), Similarly after completion of a specific function POP its corresponding
AR. So when main() is completed POP AR of main(). Now stack is empty.
In the winding phase the stack content increases as new Activation Records(AR) are
created and pushed into the stack for each invocation of the function. In the
unwinding phase the Activation Records are popped from the stack in LIFO order till
the original call returns.
Examples of Recursion
Q1. Write a program using recursion to find the summation of numbers from 1 to n.
Ans: We can say ‘sum of numbers from 1 to n can be represented as sum of
numbers from 1 to n-1 plus n’ i.e.
Sum of numbers from 1 to n = n + Sum of numbers from 1 to n-1
= n + n-1 + Sum of numbers from 1 to n-2
= n+ n-1 + n-2 + ................ +1
The program which implements the above logic is as follows:

#include<stdio.h>
int sum(int);
void main()
{
intn,s;
printf(“Enter a number”);
scanf(“%d”,&n);
s=sum(n);
printf(“Sum of numbers from 1 to %d is %d”,n,s);
}
int sum(int m)
{
int r;
if(m==1)
return (1);
else
r=m+sum(m-1); /*Recursive Call*/
return r;
}
Output:
Enter a number 5
15

Q2. Write a program using recursion to find power of a number i.e. nm


Ans:
We can write,
nm= n*nm-1
=n*n*nm-2
=n*n*n*……………m times *nm-m
The program which implements the above logic is as follows:

#include<stdio.h>
int power(int,int);
void main()
{
intn,m,k;
printf(“Enter the value of n and m”);
scanf(“%d%d”,&n,&m);
k=power(n,m);
printf(“The value of nmfor n=%d and m=%d is %d”,n,m,k);
}
int power(int x, int y)
{
if(y==0)
{
return 1;
}
else
{
return(x*power(x,y-1));
}
}
Output:
Enter the value of n and m
3
5
The value of nmfor n=3 and m=5 is 243
Q3:Write a program to print Fibonacci Series upto a given number of terms.
Ans:
Fibonacci series is a sequence of integers in which the first two integers are 1 and
from third integer onwards each integer is the sum of previous two integers of the
sequence i.e.
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ……..........................
The program which implements the above logic is as follows:

#include<stdio.h>
int Fibonacci(int);
void main()
{
intterm,i;
printf(“Enter the number of terms of Fibonacci Series which is going to be printed”);
scanf(“%d”,&term);
for(i=0;i<term;i++)
{
printf(“%d”,Fibonacci(i));
}
}
int Fibonacci(int x)
{
if(x==0 || x==1) return 1;
else
return (Fibonacci(x-1) + Fibonacci(x-2));
}
Output:
Enter the number of terms of Fibonacci Series which is going to be printed 6
1 1 2 3 5 8 13
Exercise

1.What do you mean by function?


2. Why function is used in a program?
3. What do you mean by call by value and call by address?
4. What is the difference between actual arguments and formal arguments?
5. How many types of functions are available in C?
6. How many arguments can be used in a function?
7. Mulitiplytwo numbers using
a) with argument with return type
b) with argument without return type
c) without argument without return type
d) without argument with return type
8. Write a program using function to calculate the factorial of a number entered
through the keyboard.
9. Write a function power(n,m), to calculate the value of n raised to m.
10. A year is entered by the user through keyboard. Write a function to determine
whether the year is a leap year or not.
11. Write a function that inputs a number and prints the multiplication table of that
number.
12. Write a programme to check whether a number is prime or Armstrong or perfect
number using function.
13.Write a programme to find the biggest of three number using function.
14.Write a programme to swap two number using call by value and call by reference
technique.
15. Write a programme to concatenate two string using function.
16.Write a programme to convert a decimal number to binary number using
recursion.
17.What is the use of recursion in a program, Explain?
18. What is the difference between iteration and recursion?
19. What is the use of return statement in function ?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy