Unit 4
Unit 4
Unit 4
Function 2
Definition of function 2
Declaration of function 2
Pass by value 12
Pass by reference 14
Recursion 16
Pointers 21
Definition 21
Initialization 24
Pointers arithmetic 26
1
Function - definition of function - Declaration of function - Pass by value - Pass by
reference - Recursion - Pointers - Definition - Initialization - Pointers arithmetic -
Pointers and arrays- Example Problems.
4.1 Functions
1. Return type
2. Function name
3. Parameter list
4. Local variables declaration
5. Statements
6. Return value.
2
returntype function name (argument1,argument 2)
statements;
return variables;
The function with return value must be the data type, that is return type and return
value must be of same data type.
3
The return Keyword is used only when a function returns a value. If you want to
return more than one values, pointers can be used to directly change the values in address
instead of returning those values to the function.
Function_name();
Function_name(parameters);
Parameters
The variables are used in between calling function and called function is called
parameters. There are two types of parameters,
Actual parameter:
The parameters in which are transferred from the calling function to the called
program.
Formal parameter:
The parameters are transferred from the called function to the calling program.
Example:
main()
{
…
fun(parameter1,parameter2);
}
fun(parameter3,parameter4);
4
When declaring a function follows the given points:
Example:
#include <stdio.h>
int add ( int x, int y );
int main()
{
int x;
int y;
printf( "Please input two numbers to be added: " );
scanf( "%d", &x );
scanf( "%d", &y );
printf( "The sum of your two numbers are %d\n", add( x, y ) );
getchar();
}
int add (int x, int y)
{
return x + y;
}
Output:
5
Please input two numbers to be added: 3 4
The sum of your two numbers are 7
Local:
These variables only exist inside the specific function that creates them. They are unknown
to other functions and to the main program. Local variables cease to exist once the function
that created them is completed.
Global:
These variables can be accessed (ie known) by any function comprising the program. They
are implemented by associating memory locations with variable names. If a variable of the
same name is declared both within a function and outside of it, the function will use the
variable that was declared within it and ignore the global one.
6
return 0;
}
Output:
The sum of 10+20+30 = 60
It is one of the simplest types of function in C. This type of function which does not
return any value cannot be used in an expression it can be used only as independent
statement.
7
A C function without any arguments means you cannot pass data (values like int, char
etc) to the called function. Similarly, function with no return type does not pass back data to
the calling function. Let’s have an example to illustrate this.
In this program , no data transfer takes place between the calling function and the called
function. i.e.. the called program does not receive any data from the calling program and does
not send back any value to the calling program.
#include<stdio.h>
#include<conio.h>
void printline()
{
int i;
printf("\n");
for(i=0;i<10;i++)
{
printf(‘*’);
}
printf("\n");
}
void main()
{
clrscr();
printf("Welcome");
printline();
getch();
}
Output
Welcome
**********
8
2. Functions with arguments and no return value.
#include<stdio.h>
#include<conio.h>
void add(int x, int y)
{
int result;
result = x+y;
printf("Sum of %d and %d is %d.\n\n",x,y,result);
}
void main()
{
clrscr();
add(14,15);
getch();
}
Output:
Sum of 14 and 15 is 29
Output:
Result : 85
Void function1() Void function2()
{ No argument passing {
4. Functions with no arguments but returns value.
------ -----
Res= Function2(); return value Return (z)
10
…… }
}
#include<stdio.h>
#include<conio.h>
int add()
{
int a;
printf("Enter a no : ");
scanf("%d",&a);
return(a);
}
void main()
{
int z;
clrscr();
z = add();
printf("\nYou entered : %d.", z);
getch();
}
Output:
Enter a no : 5
You entered: 5
Output:
Sum = 21
Sub = -1
Pass by Value, means that a copy of the data is made and stored by way of the name
of the parameter. Any changes to the parameter have NO affect on data in the calling
function.
When the value is passed directly to the function it is called call by value. In call by
value only a copy of the variable is only passed so any changes made to the variable does not
reflects in the calling function.
13
4.3. Pass by Reference
A reference parameter "refers" to the original data in the calling function. Thus any
changes made to the parameter are also made to the original variable.
1. Arrays
2. The ampersand used in the function prototype.
function ( & parameter_name )
#include<stdio.h>
#include<conio.h>
swap(int *, int *);
void main()
{
int x,y;
printf("Enter two nos");
scanf("%d %d",&x,&y);
printf("\nBefore swapping:x=%d y=%d",x,y);
swap(&x,&y);
printf("\nAfter swapping :x=%d y=%d",x,y);
getch();
}
swap(int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
}
14
30
Before swapping :
15
30
After swapping :
30
15
Here, the changes of the formal parameters Here, the address of arguments are copied
cannot affect the actual parameters, because into the parameters inside the function, the
formal arguments are photocopy of actual address is used to access the actual arguments
arguments. used in the call. Hence changes made in the
arguments are permanent.
Memory location occupied by formal and Memory location occupied by formal and
actual arguments is different actual arguments is same and there is a
saving of memory location
Since a new location is created, this method Since the existing memory location is used
is slow through its address, this method is fast
The process of passing the actual value of The process of passing the actual addresss of
variables is known as “call by value”. variables is known as “call by Reference”.
4.1.5. Recursion in C:
15
Recursion is calling function by itself again and again until some specified condition
has been satisfied.
This process is used for repetitive computation in which each action is satisfied in
terms of a previous result.
Syntax:
local variables;
statements;
#include<stdio.h>
#include<conio.h>
int factorial(int n);
void main()
{
int res,x;
printf(“\n Enter the value:”);
scanf(“%d”, &x);
res=factorial(x);
printf(“The factorial of %d is ..%d”, res);
}
int factorial(int n)
{
int fact;
16
if (n==1)
return(1);
else
fact = n*factorial(n-1);
return(fact);
}
Factorial of 5 is 120
i.e., 5 * factorial(5-1)
5 * 4*factorial(4-1)
5 * 4*3*factorial(3-1)
5 * 4*3*2* factorial(2-1)
5 * 4*3*2*1*factorial(1-1)
5*4*3*2*1
#include<stdio.h>
#include<conio.h>
int Fibonacci(int);
int main()
{
int n,c;
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\n", Fibonacci(c));
c++;
}
return 0;
17
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
#include <stdio.h>
int fibonaci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonaci(i-1) + fibonaci(i-2);
}
int main()
{
int i;
for (i = 0; i < =3; i++)
18
{
printf("%d\t%n", fibonaci(i));
}
return 0;
}
Output:
0 1 1 2 3
Example: 3
=3+sum(2)
=3+2+sum(1)
19
=3+2+1+sum(0)
=3+2+1+0
=6
Output:
Sum = 6
main() function of a C program accepts arguments from command line or from other shell
scripts by following commands.
They are,
argc
argv[]
where,
ex:
argv[3] = NULL
20
#include <stdio.h>
#include <stdlib.h>
4.2. Pointers
Normal variable stores the value whereas pointer variable stores the address of the
variable. The content of the C pointer always be a whole number i.e. address.
The indirection operators (*) returns the value of the address stored in a pointer. The
address of operator (&) returns the memory address of the variable.
Pointer is a user defined data type which creates special types of variables which
can hold the address of primitive data type like char, int, float, double or user defined data
type like function, pointer etc. or derived data type like array, structure, union, enum.
Null pointer:
int *a;
int *b;
21
b=a=0;
Pointer to pointer
int ** p;
Example
int a=5;
int *b;
int **c;
b=&a;
c=&b;
#include<stdio.h>
#include<stdlib.h>
int main() {
return (0);
22
}
Advantages
Pointers are used for efficient code.
Pointers are access memory efficiently and simplicity.
Array Pointer
Array allocates space automatically Pointer is explicitly assigned to point to an
allocated
space.
It cannot be resized. It can be resized using realloc ().
It cannot be reassigned. Pointers can be reassigned.
Size of(array name) gives the number of Sizeof(pointer name) returns the number of
bytes occupied by the array. bytes used to store the pointer variable
Only zero (0) and NULL can be assigned to a pointer no other number can be
assigned to a pointer.
int *p=0;
int *p=NULL;
int *p = null.
The value of null pointer is 0. If pointer is assigned to NULL, it means it is pointing to
nothing. The size of any pointer is 2 byte (for 16 bit compiler).
23
Assigning variable to a pointer:
int a; *p;
p = &a;
A pointer variable p is assigned the address of the variable a. The address of the variables will
be different every time.
& symbol is used to get the address of the variable.
* symbol is used to get the value of the variable.
About variable a:
1. Name of variable : a
2. Value of variable which it keeps: 5
3. Address where it has stored in memory : 1025 (assume)
Output
24
Address of age =265432
Address++ = Address
Address-- = Address
++Address = Address
25
--Address = Address
If we will add or subtract a number from an address result will also be an address.
New address = old address + number*size of data type which pointer is pointing
Or
New address = old address - number*size of data type which pointer is pointing
Example:
#include<stdio.h>
int main()
{
int *ptr=( int *)1000;
ptr=ptr+1;
printf(" %u",ptr);
return 0;
}
Output: 1002
Address - Address=Number
If you will subtract two pointers result will be a number but number will not simple
mathematical subtraction of two addresses but it follow following rule:
Address2 –address1 = subtraction of two address/size of data type which pointer points
26
Example:
Explanation:
Here two pointer p and temp are of same type and both are pointing to int data type varaible.
p-temp = (1004-1000)/sizeof(int)
=4/2
=2
#include<stdio.h>
int main()
{
int *p=(int *)1000;
int *temp;
temp=p;
p=p+2;
printf("%u %u\n",temp,p);
printf("difference= %d",p-temp);
return 0;
}
Difference= 2
Pointer to function
Example:
#include<stdio.h>
27
int * function();
int main(){
auto int *x;
int *(*ptr)();
ptr=&function;
x=(*ptr)();
printf("%d",*x);
return 0;
}
int *function(){
static int a=10;
return &a;
}
Output: 10
Here function is function whose parameter is void data type and return type is pointer to int
data type.
x=(*ptr)()
x=(*&functyion)() //ptr=&function
x=&a
Pointer to structure:
Example:
#include<stdio.h>
28
struct address
{
char *name;
char street[10];
int pin;
} cus;
cus={"pandi","H",625003},*p=&cus;
int main()
{
printf("%s %s",p->name,(*p).street);
return 0;
}
• -> and (*). Both are same thing. These operators are used to access data member of
structure by using structure’s pointer.
Output:
pandi H
Pointer to union:
Example:
#include<stdio.h>
union address{
char *name;
char street[10];
int pin;
};
int main(){
union address emp,*p;
29
emp.name="jai";
p=&emp;
printf("%s %s",p->name,(*p).name);
return 0;
}
• -> and (*). Both are same thing. These operators are used to access data member of
union by using union’s pointer.
Output:
jai
Here an array is declared, the memory should be allocated in contiguous location. The
memory location as a base address plus sufficient amount of storage .
farray [][3];
It is two dimension array and its content are float constants. array [3]:It is one
dimension array and its content are address of such one dimension array which content are
float constant. ptr: It is pointer to one dimension array which content are address of such one
dimension array which content are float constant.
Example:
#include<stdio.h>
int main(){
static float farray[][3]={0.0f,1.0f,2.0f,3.0f,4.0f,5.0f,6.0f,7.0f,8.0f};
30
float (*array[3])[3]={&farray[0],&farray[1],&farray[2]};
float (*(*ptr)[])[3]=&array;
printf("%f ",2[(*(**ptr+1))]);
return 0;
}
Output: 5.000000
Example:
#include<stdio.h>
char display(char (*)[]);
int main(){
char c;
char character[]={65,66,67,68};
char (*ptr)[]=&character;
c=display(ptr);
printf("%c",c);
return 0;
}
char display(char (*s)[]){
**s+=2;
return **s;
}
Output: C
31
Here function display is passing pointer to array of characters and returning char data type.
**s+=2
=>**s=**s+2
=>**ptr=**ptr+2 //s=ptr
When an array name is passed to a function, what is passed is the location of the
initial element. Within the called function, this argument is a local variable, and so an array
name parameter is a pointer, that is, a variable containing an address. We can use this fact to
write another version of strlen, which computes the length of a string.
Since s is a pointer, incrementing it is perfectly legal; s++ has no effect on the character
string in the function.
32
A pointer to such an array which contents are integer numbers is known as pointer to
array of integer.
#include<stdio.h>
int main()
{
static int i,j,k;
int *(*ptr)[];
int *array[3]={&i,&j,&k};
ptr=&array;
j=i+++k+10;
++(**ptr);
printf("%d",***ptr);
return 0;
}
Output: 10
Note: In the above figure upper part of box represent content and lower part represent
memory address. We have assumed arbitrary address.
j=i+++k+10
=i++ + k+10
=0 +0 +10=10
=*array [1]
=*&j
=j
33
=10
Part –A (2-mark)
1. Define a C function to exchange the content of two variables
2. What is an argument? Differentiate between formal arguments and actual
arguments.
3. How a variable is declared to be a pointer?
4. Is it possible to refer to the elements of an array by using pointer notation? If so, give
an example.
5. What is recursion? Give its applications.
6. List out the differences between call by value and call by reference?
7. What are the advantages of pointers.
8. What is the need of functions?
10. What is a pointer? How to declare a pointer variable.
11. Mention the operators used in pointer.
12. What is pointer-to-pointer?
PART –B
34