1. Function
A function is a block of code that performs a specific task. It has a
name and it is reusable .It can be executed from as many different parts
in a program as required, it can also return a value to calling program.
All executable code resides within a function. It takes input, does
something with it, then give the answer. A C program consists of one or
more functions.
A computer program cannot handle all the tasks by itself. It requests
other program like entitiescalled functions in C. We pass information to the
function called arguments which specified when the function is called. A
function either can return a value or returns nothing. Function is a
subprogram that helps reduce coding.
Syntax
return-type function-name (arguments);
main()
{
.
.
statements within main function;
printf("%d", function-name (arguments)); //function call
.
}
return-type function-name (arguments) //function definition
{
.
.
statements within user-defined function;
.
2. return variablename;
}
Simple Example of Function in C
#include<stdio.h>
int adition(int, int); //Function Declaration
int addition(int a, int b) //Function Definition
{
int r;
r=a + b;
return (r);
}
int main()
{
int z;
z= addion(10,3); //Function Call
printf ("The Result is %d", z);
return 0;
}
A function is a group of statements that together perform a task. Every C
program has at least one function, which is main(), and all the most trivial
programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division is such that each
function performs a specific task.
A function declaration tells the compiler about a function's name, return
type, and parameters. A function definition provides the actual body of the
function.
Types of Function
There are two types of functions they are,
1. Library Functions
3. 2. User Defined functions
1. Library Functions
C provides many pre-defined functions to perform a task, those functions are
defined in an appropriate header files.
printf()
scanf()
strlen()
sqrt() and so on
2. User Defined Functions
C allows users or programmers to define a function according to their
requirement. The main() function is also a user-defined function because the
statements inside the main function is defined by the user, only the function
name is defined in a library.
Function Declaration
The function declaration statement informs the compiler about a function return
type, function name and parameters or arguments type.
Defining a Function
The general form of a function definition in C programming language is as follows
−
return_type function_name( parameter list )
{
body of the function
}
A function definition in C programming consists of a function header and
a function body. Here are all the parts of a function −
Return Type − A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the
keyword void.
Function Name − This is the actual name of the function. The function
name and the parameter list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is
invoked, you pass a value to the parameter. This value is referred to as
4. actual parameter or argument. The parameter list refers to the type, order,
and number of the parameters of a function. Parameters are optional; that
is, a function may contain no parameters.
Function Body − The function body contains a collection of statements that
define what the function does.
Whatever is written with in { } is the body of the function
Functions
The following example program will clearly explain the concept of functions
#include <stdio.h>
int main()
{
//main function definition
int a = 5, b = 10;
int sum;
printf("The value of a and b : %d %d ", a, b);
sum = add(a, b); //function call
printf("nsum = %d ", sum);
}
//function definition
int add(int a, int b)
{
int c;
c = a + b;
return c; //returns a integer value to the calling function
}
output
The value of a and b : 5 10
sum = 15
5. Types
The user-defined functions are classified into four types, according to
parameters and return value.
1. Functions without arguments but with return values
2. Functions without arguments and without return values
3. Functions with arguments but without return values
4. Functions with arguments and with return values
#1 Functions Without Arguments Without Return Values
The calling function will not send parameters to the called function and called
function will not pass the return value to the calling function.
C program - Functions Without Arguments Without Return Values
function1.c
#include <stdio.h>
void add(); //function declaration
int main()
{
//main function definition
add(); //function call without passing arguments
}
//function definition
void add()
{
int a = 5, b = 10;
int c;
printf(" The values of a and b : %d %d ", a, b);
c = a + b;
printf(" nsum : %d ", c);
//no return values to the calling function
}
6. The values of a and b : 5 10
sum = 15
Note:
The program illustrates that, there are no parameters passed through the
calling function and no return value to the calling function main().
#2 Functions With Arguments Without Return Values
The calling function will pass parameters to the called function but called
function will not pass the return value to the calling function.
C program - Functions With Arguments Without Return Values
function2.c
#include <stdio.h>
void add(int,int); //function declaration
int main()
{
//main function definition
int sum;
int a = 5, b = 10;
printf(" The values of a and b : %d %d ", a, b);
add( a, b); //function call with passing arguments to called function
}
// function definition
void add(int a, int b)
{
int c;
c = a + b;
printf(" nsum : %d ", c);
//no return values to the calling function main
}
The values of a and b : 5 10
7. sum = 15
Note:
The program illustrates that, parameters are passed to the called function(add)
from calling function(main) but no return values are passed from called
function(add) to the calling function (main).
#3 Functions Without Arguments With Return Values
The calling function will not pass parameters to the called function but called
function will pass the return value to the calling function.
C program - Functions Without Arguments With Return Values
function3.c
#include <stdio.h>
int add(); //function declaration
int main()
{
//main function definition
int sum;
sum = add(); //function call without passing arguments to called function
printf(" nsum = %d ", sum);
}
// function definition
int add()
{
int c;
int a = 5, b = 10;
printf(" The values of a and b : %d %d ", a, b);
c = a + b;
return c; //passing return values to the calling function main
}
The values of a and b : 5 10
8. sum = 15
Note:
The program illustrates that, no parameters are passed to the called
function(add) from calling function(main) but return value is passed from
called function(add) to the calling function (main). The return values is
assigned to the variable sum.
#4 Functions With Arguments With Return Values
The calling function will pass parameters to the called function and called
function also pass the return value to the calling function.
4. Functions With Arguments With Return Values
function4.c
#include <stdio.h>
int add(int, int); //function declaration
int main()
{
//main function definition
int sum;
int a = 5, b = 10;
printf(" The values of a and b : %d %d ", a, b);
sum = add( a, b); //function call with passing arguments
printf(" nsum = %d ", sum);
}
// function definition
int add(int a, int b)
{
int c;
c = a + b;
return c; //passing return values to the calling function main
}
The values of a and b : 5 10
9. sum = 15
Given below is the source code for a function called max(). This function takes
two parameters num1 and num2 and returns the maximum value between the
two −
/* function returning the max between two numbers */
int max(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Function Declarations
A function declaration tells the compiler about a function name and how to call
the function. The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function declaration is as follows −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is
required, so the following is also a valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and
you call that function in another file. In such case, you should declare the function
at the top of the file calling the function.
Calling a Function
While creating a C function, you give a definition of what the function has to do.
To use a function, you will have to call that function to perform the defined task.
10. When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task and when its return statement
is executed or when its function-ending closing brace is reached, it returns the
program control back to the main program.
To call a function, you simply need to pass the required parameters along with
the function name, and if the function returns a value, then you can store the
returned value. For example –
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main () {
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %dn", ret );
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
We have kept max() along with main() and compiled the source code. While
running the final executable, it would produce the following result −
11. Max value is : 200
Function Arguments
If a function is to use arguments, it must declare variables that accept the values
of the arguments. These variables are called the formal parameters of the
function.
Formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to
a function
Sr.No. Call Type & Description
1 Call by value
This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument.
2 Call by reference
This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the
actual argument used in the call. This means that changes made to
the parameter affect the argument.
By default, C uses call by value to pass arguments. In general, it means the
code within a function cannot alter the arguments used to call the function.
call by Value
The call by value method of passing arguments to a function copies the actual
value of an argument into the formal parameter of the function. In this case,
changes made to the parameter inside the function have no effect on the
argument.
By default, C programming uses call by value to pass arguments. In general, it
means the code within a function cannot alter the arguments used to call the
function. Consider the function swap() definition as follows.
/* function definition to swap the values */
12. void swap(int x, int y) {
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
Now, let us call the function swap() by passing actual values as in the following
example −
#include <stdio.h>
/* function declaration */
void swap(int x, int y);
int main () {
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %dn", a );
printf("Before swap, value of b : %dn", b );
/* calling a function to swap the values */
swap(a, b);
printf("After swap, value of a : %dn", a );
printf("After swap, value of b : %dn", b );
return 0;
}
void swap(int x, int y) {
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
13. }
Let us put the above code in a single C file, compile and execute it, it will produce
the following result −
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 100
After swap, value of b : 200
It shows that there are no changes in the values, though they had been changed
inside the function.
call by reference
The call by reference method of passing arguments to a function copies
the address of an argument into the formal parameter. Inside the function, the
address is used to access the actual argument used in the call. It means the
changes made to the parameter affect the passed argument.
To pass a value by reference, argument pointers are passed to the
functions just like any other value. So accordingly you need to declare the
function parameters as pointer types as in the following function swap(),
which exchanges the values of the two integer variables pointed to, by their
arguments.
/* function definition to swap the values */
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
Let us now call the function swap() by passing values by reference as in the
following example −
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
14. printf("Before swap, value of a : %dn", a );
printf("Before swap, value of b : %dn", b );
/* calling a function to swap the values */
swap(&a, &b);
printf("After swap, value of a : %dn", a );
printf("After swap, value of b : %dn", b );
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value of x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
Let us put the above code in a single C file, compile and execute it, to produce the
following result −
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100
It shows that the change has reflected outside the function as well, unlike call by
value where the changes do not reflect outside the function.
Scope
A scope in any programming is a of region the program where a defined variable
can have its existence and beyond that variable it cannot be accessed. There are
three places where variables can be declared in C programming language −
Inside a function or a block which is called local variables.
Outside of all functions which is called global variables.
In the definition of function parameters which are called formal parameters.
Let us understand what are local and global variables, and formal parameters.
Local Variables
15. Variables that are declared inside a function or block are called local variables.
They can be used only by statements that are inside that function or block of
code. Local variables are not known to functions outside their own. The following
example shows how local variables are used. Here all the variables a, b, and c are
local to main() function.
#include <stdio.h>
int main()
{
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %dn", a, b, c);
return 0;
}
Global Variables
Global variables are defined outside a function, usually on top of the program.
Global variables hold their values throughout the lifetime of your program and
they can be accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration. The
following program show how global variables are used in a program.
#include <stdio.h>
/* global variable declaration */
int g;
int main ()
{
/* local variable declaration */
int a, b;
16. /* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %dn", a, b, g);
return 0;
}
A program can have same name for local and global variables but the value of
local variable inside a function will take preference. Here is an example −
Live Demo
#include <stdio.h>
/* global variable declaration */
int g = 20;
int main () {
/* local variable declaration */
int g = 10;
printf ("value of g = %dn", g);
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of g = 10
Formal Parameters
Formal parameters, are treated as local variables with-in a function and they take
precedence over global variables. Following is an example −
#include <stdio.h>
/* global variable declaration */
int a = 20;
int main ()
{
17. /* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %dn", a);
c = sum( a, b);
printf ("value of c in main() = %dn", c);
return 0;
}
/* function to add two integers */
int sum(int a, int b)
{
printf ("value of a in sum() = %dn", a);
printf ("value of b in sum() = %dn", b);
return a + b;
}
When the above code is compiled and executed, it produces the following result −
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
Initializing Local and Global Variables
When a local variable is defined, it is not initialized by the system, you must
initialize it yourself. Global variables are initialized automatically by the system
when you define them as follows −
Data Type Initial Default Value
Int 0
Char '0'
18. Float 0
Double 0
Pointer NULL
It is a good programming practice to initialize variables properly, otherwise your
program may produce unexpected results, because uninitialized variables will take
some garbage value already available at their memory location.
Passing Array to Function in C
In C, there are various general problems which requires passing more than one
variable of the same type to a function. For example, consider a function which
sorts the 10 elements in ascending order. Such a function requires 10 numbers to
be passed as the actual parameters from the main function. Here, instead of
declaring 10 different numbers and then passing into the function, we can declare
and initialize an array and pass that into the function. This will resolve all the
complexity since the function will now work for any number of values.
As we know that the array_name contains the address of the first element. Here,
we must notice that we need to pass only the name of the array in the function
which is intended to accept an array. The array defined as the formal parameter
will automatically refer to the array specified by the array name defined as an
actual parameter.
Consider the following syntax to pass an array to the function.
1. functionname(arrayname);//passing array
Methods to declare a function that receives an array as an argument
There are 3 ways to declare the function which is intended to receive an array as
an argument.
First way:
return_type function(type arrayname[])
Declaring blank subscript notation [] is the widely used technique.utorial
Second way:
19. return_type function(type arrayname[SIZE])
Optionally, we can define size in subscript notation [].
Third way:
return_type function(type *arrayname)
a[5]=1,3,5,6,7
*a[3]=6
You can also use the concept of a pointer. In pointer chapter, we will learn about
it.
C language passing an array to function example
#include<stdio.h>
int minarray(int arr[],int size)
{
int min=arr[0];
int i=0;
for(i=1;i<size;i++)
{
if(min>arr[i])
{
min=arr[i];
}
}//end of for
return min;
}//end of function
int main()
{
int i=0,min=0;
int numbers[]={4,5,7,3,8,9};//declaration of array
min=minarray(numbers,6);//passing array with size
printf("minimum number is %d n",min);
20. return 0;
}
Output
minimum number is 3
C function to sort the array
#include<stdio.h>
void Bubble_Sort(int[]);
void main ()
{
int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
Bubble_Sort(arr);
}
void Bubble_Sort(int a[]) //array a[] points to arr.
{
int i, j,temp;
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...n");
for(i = 0; i<10; i++)
{
printf("%dn",a[i]);
}
}
Output
21. Printing Sorted Element List ...
7
9
10
12
23
23
34
44
78
101
Returning array from the function
As we know that, a function can not return more than one value. However, if we
try to write the return statement as return a, b, c; to return three values (a,b,c),
the function will return the last mentioned value which is c in our case. In some
problems, we may need to return multiple values from a function. In such cases,
an array is returned from the function.
Returning an array is similar to passing the array into the function. The name of
the array is returned from the function. To make a function returning an array, the
following syntax is used.
int * Function_name()
{
//some statements;
return array_type;
}
To store the array returned from the function, we can define a pointer which points
to that array. We can traverse the array by increasing that pointer since pointer
initially points to the base address of the array. Consider the following example
that contains a function returning the sorted array.
#include<stdio.h>
int* Bubble_Sort(int[]);
void main ()
{
int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
int *p = Bubble_Sort(arr), i;
printf("printing sorted elements ...n");
for(i=0;i<10;i++)
22. {
printf("%dn",*(p+i));
}
}
int* Bubble_Sort(int a[]) //array a[] points to arr.
{
int i, j,temp;
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a;
}
Output
Printing Sorted Element List ...
7
9
10
12
23
23
34
44
78
101
Return an Array in C
What is an Array?
23. An array is a type of data structure that stores a fixed-size of a homogeneous
collection of data. In short, we can say that array is a collection of variables of the
same type.
For example, if we want to declare 'n' number of variables, n1, n2...n., if we create
all these variables individually, then it becomes a very tedious task. In such a
case, we create an array of variables having the same type. Each element of an
array can be accessed using an index of the element.
Let's first see how to pass a single-dimensional array to a function.
Passing array to a function
#include <stdio.h>
void getarray(int arr[])
{
printf("Elements of array are : ");
for(int i=0;i<5;i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
int arr[5]={45,67,34,78,90};
getarray(arr);
return 0;
}
In the above program, we have first created the array arr[] and then we pass this
array to the function getarray(). The getarray() function prints all the elements of
the array arr[].
Output
Exception Handling in Java - Javatpoint
24. Passing array to a function as a pointer
Now, we will see how to pass an array to a function as a pointer.
#include <stdio.h>
void printarray(char *arr)
{
printf("Elements of array are : ");
for(int i=0;i<5;i++)
{
printf("%c ", arr[i]);
}
}
int main()
{
char arr[5]={'A','B','C','D','E'};
printarray(arr);
return 0;
}
In the above code, we have passed the array to the function as a pointer. The
function printarray() prints the elements of an array.
Output
25. Note: From the above examples, we observe that array is passed to a function as
a reference which means that array also persist outside the function.
How to return an array from a function
Returning pointer pointing to the array
#include <stdio.h>
int *getarray()
{
int arr[5];
printf("Enter the elements in an array : ");
for(int i=0;i<5;i++)
{
scanf("%d", &arr[i]);
}
return arr;
}
int main()
{
int *n;
n=getarray();
printf("nElements of array are :");
for(int i=0;i<5;i++)
{
printf("%d", n[i]);
}
return 0;
}
26. In the above program, getarray() function returns a variable 'arr'. It returns a
local variable, but it is an illegal memory location to be returned, which is allocated
within a function in the stack. Since the program control comes back to
the main() function, and all the variables in a stack are freed. Therefore, we can
say that this program is returning memory location, which is already de-allocated,
so the output of the program is a segmentation fault.
Output
Pointer to an Array in C
It is most likely that you would not understand this section until you are through
with the chapter 'Pointers'.
Assuming you have some understanding of pointers in C, let us start: An array
name is a constant pointer to the first element of the array. Therefore, in the
declaration −
double balance[50];
balance is a pointer to &balance[0], which is the address of the first element of
the array balance. Thus, the following program fragment assigns p as the address
of the first element of balance −
double *p;
double balance[10];
p = balance;
It is legal to use array names as constant pointers, and vice versa. Therefore,
*(balance + 4) is a legitimate way of accessing the data at balance[4].
Once you store the address of the first element in 'p', you can access the array
elements using *p, *(p+1), *(p+2) and so on. Given below is the example to
show all the concepts discussed above −
Live Demo
#include <stdio.h>
int main () {
27. /* an array with 5 elements */
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
int i;
p = balance;
/* output each array element's value */
printf( "Array values using pointern");
for ( i = 0; i < 5; i++ ) {
printf("*(p + %d) : %fn", i, *(p + i) );
}
printf( "Array values using balance as addressn");
for ( i = 0; i < 5; i++ ) {
printf("*(balance + %d) : %fn", i, *(balance + i) );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Array values using pointer
*(p + 0) : 1000.000000
*(p + 1) : 2.000000
*(p + 2) : 3.400000
*(p + 3) : 17.000000
*(p + 4) : 50.000000
Array values using balance as address
*(balance + 0) : 1000.000000
*(balance + 1) : 2.000000
*(balance + 2) : 3.400000
*(balance + 3) : 17.000000
*(balance + 4) : 50.000000
In the above example, p is a pointer to double, which means it can store the
address of a variable of double type. Once we have the address in p, *p will give
us the value available at the address stored in p, as we have shown in the above
example.
What are different types of storage classes in ‗C‘
Variables in C differ in behavior. The behavior depends on the storage class
a variable may assume. From C compiler‟s point of view, a variable name
28. identifies some physical location within the computer where the string of bits
representing the variable‟s value is stored. There are four storage classes in
C:
(a) Automatic storage class
(b) Register storage class
(c) Static storage class
(d) External storage class
(a) Automatic Storage Class:-
The features of a variable defined to have an automatic storage class are as
under:
Keyword Auto
Storage Memory.
Default initial
value
An unpredictable value, which is often called a
garbage value.
Scope Local to the block in which the variable is defined.
Life Till the control remains within the block in
which thevariable is defined
Following program shows how an automatic storage class variable is
declared, and the fact that if the variable is not initialized it contains a
garbage value.
main( )
{
auto int i, j ;
printf ( "n%d %d", i, j ) ;
}
When you run this program you may get different values, since garbage
values are unpredictable. So always make it a point that you initialize the
automatic variables properly, otherwise you are likely to get unexpected
results. Scope and life of an automatic variable is illustrated in the following
program.
main( )
{
auto int i = 1 ;
29. {
auto int i = 2 ;
{
auto int i = 3 ;
printf ( "n%d
", i ) ;
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}
Static Storage Class:-
The features of a variable defined to have a static storage class are as under:
Keyword Static
Storage Memory.
Default initial
value
Zero.
Scope Local to the block in which the variable is
defined.
Life Value of the variable persists between different
function calls
30. The following program demonstrates the details of static storage class:
Extern Storage Class:-
The features of a variable whose storage class has been defined as external are
as follows:
Keyword Extern
Storage Memory
default initial
value
Zero
Scope Global
Lif
e
As long as the program execution
does not cometo end
External variables differ from those we have already discussed in that their
scope is global, not local. External variables are declared outside all
functions, yet are available to all functions that care to use them. Here is an
example to illustrate this fact.
Ex:
#include<stdio.h>
extern int i;
void main()
{
31. printf(“i=%d”,i);
}
Register Storage Class:-
The features of a variable defined to be of register storage class are as under:
Keyword Register
Storage CPU
Registers
default initial
value
An unpredictable value, which is often called a
garbage value.
Scope Local to the block in which the variable is
defined.
Life Till the control remains within the block in which
the variableis defined.
A value stored in a CPU register can always be accessed faster than the one
that is stored in memory. Therefore, if a variable is used at many places in a
program it is better to declare its storage class as register. A good example
of frequently used variables is loop counters. We can name their storage
class as register.
main( )
{
register int i ;
for ( i = 1 ; i <= 10 ; i++ )
printf ( "n%d", i ) ;
}
scope rules in C
32. Scope: Scope of a variable is the part of program in which it can be used
Scope rules
The rules are as under:
- Use static storage class only if you want the value of a variable to persist
between different function calls.
- Use register storage class for only those variables that are being used
very often in a program. Reason is, there are very few CPU registers at our
disposal and many of them might be busy doing something else. Make
careful utilization of the scarce resources. A typical application of register
storage class is loop counters, which get used a number of times in a
program.
- Use extern storage class for only those variables that are being used by
almost all the functions in the program. This would avoid unnecessary
passing of these variables as arguments when making a function call.
Declaring all the variables as extern would amount to a lot of wastage of
memory space because these variables would remain active throughout
the life of the program.
- If we don‟t have any of the express needs mentioned above, then use the
auto storage class. In fact most of the times we end up using the auto
variables, because often it so happens that once we have used the
variables in a function we don‟t mind loosing them.
What is recursive function? Write syntax for recursive functions.
Recursion
Recursion is a process by which a function calls itself repeatedly, until some
specified condition has been satisfied.
When a function calls itself, a new set of local variables and parameters are
allocated storage on the stack, and the function code is executed from the
top with these new variables. A recursive call does not make a new copy of
the function. Only the values being operated upon are new. As each
recursive call returns, the old local variables and parameters are removed
from the stack, and execution resumes immediately after the recursive call
inside the function.
The main advantage of recursive functions is that we can use them to create
clearer and simpler versions of several programs.
33. Syntax:-
A function is recursive if it can call itself; either directly:
void f( )
{
f( );
}
(or) indirectly:
void f( )
{
g( );
}
void g( )
{
f( );
}
Recursion rule 1: Every recursive method must have a base case -- a
condition under which norecursive call is made -- to prevent infinite
recursion.
Recursion rule 2: Every recursive method must make progress toward
the base case to preventinfinite recursion
3. Write a program to find factorial of a number
using recursion.Ans:
#include<stdio.h>
int
fact(int);
main()
{
int n,f;
printf(“n Enter any number:”);
scanf(“%d”,&n);f=fact(n);
printf(“n Factorial of %d is %d”,n,f);
}
int fact(int n)
{
int f;
34. if(n==0||n==1)
//base casef=1;
else
f=n*fact(n-1);
//recursive casereturn
f;
}
Output:- Enter any
number: 5
Factorial of 5 is
120
4. Differentiate between recursion and non-recursion.
Ans:
Recursion:- Recursion is a process by which a function calls itself repeatedly,
until somespecified condition has been satisfied.
When a function calls itself, a new set of local variables and parameters are
allocated storage on the stack, and the function code is executed from the top
with these new variables. A recursive call does not make a new copy of the
function. Only the values being operated upon are new. As each recursive call
returns, the old local variables and parameters are removed from the stack,
and execution resumes immediately after the recursive call inside the function.
Ex:-
void main( )
{
int n=5;
fact( n);
}
int fact( )
{
if(n==0 ||
n==1)
return 1;
else
return(n*fact(n-1));
}
35. Non-Recursion:-
Using looping statements we can handle repeated statements in „C‟. The
example of nonrecursion is given below.
Syntax:-
void main( )
{
int n=5;
res = fact(n);
printf(“%d”,res);
}
int fact( )
{
for(i=1;i<=n;i++)
{
f=f+1;
}
return f;
}
Differences:
- Recursive version of a program is slower than iterative version of a
program due to overheadof maintaining stack.
- Recursive version of a program uses more memory (for the stack) than
iterative version of aprogram.
- Sometimes, recursive version of a program is simpler to understand than
iterative version of aprogram.
5. Write a program to calculate GCD of two numbers
using recursionAns:
#include<stdio.h>
int gcd(int,int);
main()
{
int a,b;
36. printf("n Enter any two numbers:");
scanf("%d%d",&a,&b);
printf("nGCD=%d",gcd(a,b));
}
int gcd(int a,int b)
{
if(b==0)
//base case
return a;
else
return gcd(b,a%b); //recursive case
}
Write a program to generate Fibonacci series using recursive functions.Ans:
#include<stdio.h>
#include<conio.h>
void main()
{
int f,f1,f2,n,i,res;
printf("enter the limit:");
scanf("%d",&n);
printf("The fibonacci series is:");
for(i=0;i<n;i++)
{
res=fib(i);