Unit 4

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 34

INDEX

Unit-4 CONTENT PAGE NO

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

Pointers and arrays 31

UNIT IV FUNCTIONS AND POINTERS

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

4.1.1. Definition of function


Functions are derived data type. Functions are created when the same process or an
algorithm to be repeated several times in various places in the program. By creating function
the source code is reduced significantly.
Functions are used to give modularity.
The function main () invokes other functions within it. It is the first function to be
called when the program starts execution.

Functions are two types :


 Built-in functions
ex: printf, scanf, strcmp etc.

 User defined functions.

4.1.2. Initialization of functions

The user-defined function has following characteristics:

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)

local variables; // declaration of the local variables

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.

Returning function results

Using the keyword return, followed by data variables.

int add(int a,int b)


{
int c = a+b;
return (c);
}

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.

Calling the function:

Function called by function name followed by parameters.

Function_name();

Function_name(parameters);

Return variable= function_name(parameter);

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:

 The data type should be mention


 If there is no parameters passed, mention it as void
 The function with return value must be the data type, that is return type
and return value must be of same data type.
 The no. of actual parameters & formal parameters must match.
 The data type of actual parameters & formal parameters must match.

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 and global variables

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.

/* Demonstrating global variables */


#include <stdio.h>
int add( void);
int value1, value2, value3;
int add(void)
{
    auto int result;
     result = value1 + value2 + value3;
     return result;
}
int main(void)
{
   auto int result;
     value1 = 10; value2 = 20; value3 = 30;
     result = add();
printf(“The sum of %d + %d + %d is %d\n”, value1, value2, value3, result);

6
  return 0;
}

Output:
The sum of 10+20+30 = 60

Advantage of User defined function:

1. Reduce the source code


2. Easy to maintain and modify
3. It can be called anywhere in the program.

Categories of User defined function:

1. Function without return value and without argument.


2. Function without return value and with argument.
3. Function with return value and with argument.
4. Function with return value and without argument
5. Function with more than one return value

1. Functions with no arguments and no return value.

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.

Calling function called function

Void function1() Void function2()


{ No argument passing {
------ -----
Function2(); No return value ……
…… }
}

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.

Void function1() Void function2()


{ argument passing {
------ -----
Function2(); 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

Void function1() Void function2( int x)


{
3. Functions argument
with arguments and return passing
value. {
------ -----
Res = Function2(10); return value Return (z)
9
…… }
}
#include<stdio.h>
#include<conio.h>
int add(int x, int y)
{
int result;
result = x+y;
return(result);
}
void main()
{
int z;
clrscr();
z = add(9,55);
printf("Result %d.\n\n",add(30,55));
printf("Result %d.\n\n",z);
getch();
}

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

5. . Functions that return multiple values.


11
#include<stdio.h>
#include<conio.h>
void calc(int x, int y, int *add, int *sub)
{
*add = x+y;
*sub = x-y;
}
void main()
{
int a=10, b=11, p,q;
clrscr();
calc(a,b,&p,&q);
printf("Sum =  %d, Sub = %d",p,q);
getch();
}

Output:
Sum = 21

Sub = -1

4.2. Pass by Value

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.

/* ******* call by value ******* */


12
#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);
getch();
}
swap(int a,int b)
{
int t;
t=a;
a=b;
b=t;
printf("\nAfter swapping :x=%d y=%d",a,b);
}

Enter two nos


15
30
Before swapping :
15
30
After swapping :
30
15

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.

There are two ways to make a pass by reference parameter:

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;
}

Enter two nos


15

14
30

Before swapping :
15
30

After swapping :
30
15

Pass by value Pass by reference


This method copies the values of actual The process of calling a function using
parameters into the formal parameters of the pointers to pass the addresses of variables is
function. known as “call by reference”.

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:

int functionname (int x)

local variables;

functionname(y); // this is recursion

statements;

Example 1: Factorial using Recursion

#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

Example 2: Fibonacci using Recursion

#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) );
}

Similarly , recursion of Fibonacci series takes in to another way:

#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

/* To find sum of first n natural numbers using recursion.*/


#include <stdio.h>
int sum(int n);
int main(){
int n,add;
printf("Enter a positive natural integer:\n");
scanf("%d",&n);
add=sum(n);
printf("sum=%d",add);
}
int sum(int n){
if(n==0)
return n;
else
return n+sum(n-1);
}

=3+sum(2)

=3+2+sum(1)

19
=3+2+1+sum(0)

=3+2+1+0

=6

Output:

Enter a positive integer : 3

Sum = 6

Command line arguments

      main() function of a C program accepts arguments from command line or from other shell
scripts by following commands.

They are,

 argc
 argv[]

where,

argc      - Number of arguments in the command line including program name


argv[]   – This is carrying all the arguments

ex:

>prg1 hello hai

argc             =       4


argv[0]         =       “prg1”
argv[1]         =       “hello”
argv[2]         =       “hai”

argv[3] = NULL

ex: program for command line arguments

20
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) // command line arguments


{
printf("\n Program name : %s \n", argv[0]);
return 0;

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.

A pointer is a variable and contains the address of another variable. It is denoted


by ‘*’ operator. Pointers are called “address variable”.

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:

A pointer is said to be a null pointer when its right side value is 0.

It can never point valid data.

It is assigned to 0, so it is a null pointer and is not valid.

int *a;
int *b;

21
b=a=0;

a and b become null pointers

Pointer to pointer

A variable that is a pointer to a pointer must be declared using additional indirection


operator symbols in front of the name.

int ** p;

Pointer is a variable that contains the address of the another variable.

Example
int a=5;
int *b;
int **c;
b=&a;
c=&b;

Display array with addresses:

#include<stdio.h>

#include<stdlib.h>

int main() {

int a[3] = { 10, 20, 30 };

printf("\n a[0] ,value=%d : address=%u", a[0], &a[0]);

printf("\n a[1] ,value=%d : address=%u", a[1], &a[1]);

printf("\n a[2] ,value=%d : address=%u", a[2], &a[2]);

return (0);
22
}

Advantages
Pointers are used for efficient code.
Pointers are access memory efficiently and simplicity.

Difference between arrays and pointers are as follows.

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

4.2.1. Pointer –Initialization:

Assigning value to pointer:

Only zero (0) and NULL can be assigned to a pointer no other number can be
assigned to a pointer.

Consider the following examples;

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)

About variable ptr:


1. Name of variable : ptr
2. Value of variable which it keeps: 1025
3. Address where it has stored in memory : 5000 (assume)

/* accessing variable thru pointer */


#include <stdio.h>
main ()
{
int age=39;
printf(“address of age =%u’’ ,&age)
printf(“value of age =%d’’ , age)
}

Output

24
Address of age =265432

Value of age =39

We are going to add two numbers by using pointer.

/* add two numbers using pointer */


#include<stdio.h>
int main() {
int *ptr1, *ptr2;
int num;

printf("\nEnter two numbers : ");


scanf("%d %d", ptr1, ptr2);

num = *ptr1 + *ptr2;

printf("Sum = %d", num);


return (0);
}

4.2.2. Pointer Arithmetic

Rule 1: Addition arithmetic with pointers

Address + Number= Address

Address - Number= Address

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 will be:

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

Rule 2: Difference arithmetic with pointers

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:

If two pointers are of same type then:

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;
}

Output: 1000 1004

Difference= 2

Pointer to function

Function pointer definition:  A pointer which keeps address of a function is known as


function pointer

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=function() //From rule *&p=p

x=&a

So, *x = *&a = a =10

Pointer to structure:

A pointer which is pointing to a structure is known as 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;
}

• p is pointer to structure address.

• -> 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:

Pointer to union: A pointer which is pointing to a union is know as 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;
}

• p is pointer to union address.

• -> and (*). Both are same thing. These operators are used to access data member of
union by using union’s pointer.

• %s is used to print the string up to null character i.e. ‘\0’

Output:

jai

4.2.4. Pointer to array

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 .

base address = location of the first element (index 0) of the array.

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

Pointer to array of character:

A pointer to such an array which contents is character constants is known as pointer to


array of character constant.

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

=>**&character= **&character+2 //ptr=&character

=>*character=*character+2 //from rule *&p =p

=>character[0]=character[0]+2 //from rule *(p+i)=p[i]

=>character [0] =67

**s=character [0] =67

Note: ASCII value of ‘C’ is 67

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.

/* strlen: return length of string s */


int strlen(char *s)
{
int n;
for (n = 0; *s != '\0', s++)
n++;
return n;
}

Since s is a pointer, incrementing it is perfectly legal; s++ has no effect on the character
string in the function.

Pointer to array of integers:

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

***ptr = *** (&array) //ptr=&array

= **array //From rule *&p=p

//From rule array [0] =*(array+0) and ++ (**ptr)

=*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

1.Explain in detail about the function prototypes.


2. Explain in detail about parameter passing methods.
3. Describe the pass by value concept.
4. Describe the pass by reference concept.
5. Explain the concept of recursive functions in C.
6. Write short notes on: pointer arithmetic.
7. Explain in detail about pointers and array in C.

34

You might also like