Unit - 4 Notes
Unit - 4 Notes
Syllabus:
Function – Definition of Function – Declaration of Function – Pass by Value – Pass by Reference – Recursion –
Pointers – Definition – Initialization – Pointers arithmetic – Pointers and Array – Example Problems.
Introduction:
We have got various functions in our body for doing specific tasks.
o Heart for pumping blood in veins
o Lungs for breathing
o Eyes for vision
o Legs for walking
o Nose for smell
Solutions:
Similarly in programming we need something to handle our repetitive or specific task and they are called
function.
A Function
i accepts some input
ii process it
iii produces output.
Function Concept In Mathematics
f(x) = 5x -3
Where,
f - is an function name
x - is an argument or input of function
5x-3 - is an definition of an function
when x=1
f(1) = 5(1)-3
f(1) = 2
2 is the return value of function
when x=2
f(2) = 5(2)-3
f(2) = 7
7 is the return value of function
So, every function must have name, argument (input) and return (output) type.
sum(x,y) = x+y.
Where,
sum(2,3) = 2+3.
=5
Here 2,3 are arguments and 5 is the return value.
Introduction to Functions
Functions are a block of statements (called as modules) that perform a specific task assigned by the user.
Functions accept an input, perform a task and produce the output.
Input Function Output
1.Pre-Defined function
If we want to execute a block of statements again and again repeatedly, then we have to repeat the block of
statements again and again, which will increase the size of program code, but if we place the block of
statements that will be repeated inside the function, then we need not repeat the block of code again and again,
instead we can just call the function again and again.
2,3 add 5
3,4 add 7
4,5 add 9
5,6 add 11
6,7 add 13
In the above illustration only the input and output is changing, but the function add remains constant.
So we need not write add the function again and again, instead we can write the add function only once and call
it again with different sets of inputs.
2,3 5
3,4 7
4,5 add 9
5,6 11
6,7 13
5.1.3 Advantages of Writing Function
7. It is easier to understand the Program, when a program is divided into small modules
We can get overall idea of the program by just looking at the function names itself.
A function name is any variable name that the user gives to the function.
Arguments are nothing but the input that has been given to the function.The parameters can be passed to a
function by two different methods.
(a) Pass by value: In this approach only the copy of the actual variables is passed as a input to the function.
Hence any modification done inside the function will not be reflected in the actual variable.
(b) Pass by reference: In this approach the memory address of the actual variables is passed as a parameter to
the function. Hence any modification done inside the function will be reflected in the actual variable.
Parameter: The names given in the function definition are called Parameters.
Argument: The values supplied in the function call are called Arguments.
The return type is nothing but the output or result obtained after the execution of the functions.
Example
If you are going to create a function name add, that accepts two integer values as input adds the two values
and gives the result as integer value, then the function declaration would be as follows,
int add(int,int);
int getValue(void);
int square(int);
void display(void);
Note:
If function Definition is Written after the main function then only we need Prototype Declaration in
Global Declaration Section
If function Definition is written before the main function then, we don’t need write Prototype
Declaration
Function’s declaration doesn’t reserve any memory space.
Example Program
3. As the Compiler have prior information, during function calling compiler looks forward in the program
for the function definition.
Syntax
ReturnType FunctionName(ArgumenTtype with VariableName)
{
Block of statements;
}
Block of statements may include variable declarations, statements and return value etc.
Note: The return statement forces the function to return immediately eventhough if function is not yet
completed.
Another Example:
}
Here the function terminates after reaching the return statement without executing the statement “return c”
Example Program
#include<stdio.h>
int add(int a,int b) //Function Definition
{
return a+b;
}
void main()
{
int x=10,y=20;
int sum;
sum = add(x,y); // Function Calling
printf("\nSum = %d",sum);
}
Output
30
A function calling statement instructs the compiler to execute the function that is being called.
When a program calls a function, program control is transferred to the called function.
When a function is called, the called function performs the specified task and when the 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 we need to pass the required parameters along with function name and if the function returns
a value it has to be stored.
Syntax
functionName(argumentValue)
Example 1
add(5,6);
or
add(a,b);
Example 2
a = add(5,6);
or
b = add(a,b);
here a and b are varaibles that will store the values returned by the function add.
Example Program
#include<stdio.h>
int addition(int,int); // funciton declaration
void main()
{
int x=10,y=20;
int sum;
sum = addition(x,y); // Function Calling
printf("\nSum = %d",sum);
}
int addition(int a,int b) //Function Definition
{
return(a+b);
}
Output
30
It means that no input will be passed to the function and no value will be returned from the function. Everything
happens within the function.
Example
Example:
void add(int,int); //function definition
void main()
{
int a=10,b=5;
add(a,b); // function call
}
void add(int a,int b) // function definition
{
int c;
c=a+b;
printf(“%d”,c);
}
Example:
Parameter:
A parameter is an expression which is passed to a function by its caller in order for the function to perform its
task. It is an expression in the comma-separated list bound by the parentheses in a function call expression.
Actual Parameter:
Actual parameter is nothing but the arguments of the calling function. It is specified in the function calling
statement.
E.g.:
Actual
parameter
Add(A,B);
Formal Parameter
Formal Parameter Is Nothing But The Arguments Of The Called Function. It Is Specified In The Function
Formal
Definition.
E.g.:
Note: Every Time When A Function Is Called, The Value Of Actual Parameter Gets Assigned To Formal
Parameter.
Example Program
Example:
#include <stdio.h>
void sum(int i, int j, int k);
void main()
{
Int a = 5;
sum(3, 4, a); // actual arguments
}
void sum(int i, int j, int k) // formal arguments
{
int s;
s = i + j + k;
printf("sum is %d", s);
}
Here 3, 4, a are actual arguments and i,j,k are formal arguments.
#include<stdio.h>
void swap(int n1,int n2)
{
int temp;
temp = n1;
n1 = n2;
n2 = temp;
}
void main()
{
int a=50,b=70;
swap(a,b);
printf("\nA = %d",a);
printf("\nB = %d",b);
}
Output
Number 1 = 50
Number 2 = 70
Explanation
In the above example a and b are the actaul values and copy of these values are passed to the function and these
values are copied into n1, n2 variable of sum function respectively. When the values are swapped only n1 and
n2 got interchanged,whereas a and b remained unalterd.
Pass by Reference/Pointer/Address
Pass by reference we pass the memory address of the variable as input.
While passing parameter using pass by address scheme, we are passing the actual address of the
variable to the called function.
Any updates made inside the called function will modify the original copy since we are
directly modifying the content in the memory location itself.
Example Program
#include<stdio.h>
Explanation
In the above example a and b are the actual values and the memory addresses of these values are passed to the
function and when the values are swapped, the values in the memory address got interchanged, and the values a
and b have got swapped.
Note: we have used * to denote pointer variables which are capable of holding memory addresses. We have
used & to obtain the address instead of value.(you will better understand this in the section)
Note: Pass by Reference is particularly useful when we return more than one values form the function.
If we are calling any function inside another function call is known as nested function call.
Example 1
The function square( ) is inside the function sum( ) and so the function sum( ) is nested function
Function add()
int add(int a,int b)
{
int sum;
sum=square(a)+square(b);
return sum;
}
Function square()
int square(int a)
{
int sqr;
sqr=a*a;
return sqr;
}
void main()
{
int a=5,b=6;
int sumsqr;
sumsqr=add(a,b);
printf("%d",sumsqr);
}
Output:
61
In the above program when the compiler reaches the statement “sumsqr=add(a,b);” the compiler jumps to the
add() function and when the compiler reaches the statement “sum=square(a)+square(b);” it jumps to the
function square() two times, one time with the parameter as a and the other time the parameter as b.
First the value of 5*5 is calculated and the value 25 is returned to the sum() function and then the value of 6*6
is calculated and the value 36 is returned to the sum() function. Next the value of 25+36 is calculated in the
sum() function and the value 61 is returned to the main function.
Suppose, n is 5 initially. Then, during next function calls, 4 is passed to function and the value of argument
decreases by 1 in each recursive call.
When, n becomes equal to 0, the value of n is returned which is the sum numbers from 5 to 1.
sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15
Every recursive function must be provided with a way to end the recursion. In this example when, n is equal to
0, recursion function ends.
Note: Recursive function must have at least one terminating condition that can be satisfied.Otherwise, the
recursive function will call itself repeatedly until the run time stack overflows.
Example 2
Find the sum of all even numbers from 0 to 20 using function recursion.
Program:
#include<stdio.h>
void main()
{
int total;
total=sum(2);
printf("%d",total);
}
int sum(int i)
{
static int even=0;
if(i<=20)
{
even=even+i;
sum(i+2); //calling same function
}
return even;
}
Output
110
Disadvantages of recursion
It is very slow process.
function recursion can lead to infinite loop or stack over flow.
void main()
{
int age,temp;
clrscr(); // predefined function
printf("\n\tEnter Your Age = ");
scanf("%d",&age);
temp = validate(age); //Function Calling
if(temp)
printf("\n\tYou are Eligible");
else
printf("\n\tYou are not Eligible");
getch(); // predefined function
}
int validate(int age) //Function Definition user defined function
{
if(age>18)
return 1;
else
return 0;
}
5.2 Pointers
Variables in C generally hold value. An integer variable holds integer value. A floating point variable holds
floating point value. Similarly we need a data type to store the address of a variable and it is called as Pointer
variable.
Pointers are used in C program to access and manipulate the memory address.
2. The address of the variable ‘i’ is stored in another integer variable ‘j’ and which is having 65522 as its
address.
int i;
int *j; // j is a special pointer variable
i = 5;
j = &i; // i.e. j = Address of i
Note: The (&) is the address operator and it fetches the address of a
variable. A (*) symbol is appended before the variable name to notify the
compiler that it is the pointer variable.
Here j is not ordinary variable; It is special variable called pointer
variable as it stores the address of another ordinary variable.
Disadvantages of Pointer
Syntax
or
1. Pointer-type: It specifies the type of pointer. It can be int, char, float etc. This type specifies the type of
variable whose address this pointer can store.
2. Pointer-name: It can be any name specified by the user. It is just like a variable name
1. During declaration, the (*) indicates that it is a pointer variable and not a normal variable.
2. During dereferencing, the (*) indicates that, the value stored in the address, pointed by the pointer
should be accessed and not the value of the pointer(i.e the address)
The (&) is the address operator and it is used to retrieve the address of a variable.
Note: The * is used for the multiplication also but the compiler can differentiate whether it is used as a
multiplication operator or a pointer variable according to the context.
int *pointer;
2. Declare another Variable with Same Data Type as that of Pointer Variable.
int variable;
variable = 10;
4. Now initialize pointer by assigning the address of ordinary variable to pointer variable.
Pointer = &variable.
Example
Variable a b
Value 10 1010
Note: Whether it is an integer pointer or floating point every pointer variable requires only two bytes of
memory. Pointers are always initialized before using it in the program.
5.2.6 & and * Operator
The ‘*’ operator is used to obtain the value at the address contained by the pointer.
Reference operator(&)
Output
Value: 5
Address: 2686778
You will better understand the * and & operator with few more examples.
int a=10;
Variable a b
Value 10 1010
The following table show the possible ways to obtain the values using ‘*’ and ‘&’ operator.
Variable a p1 p2 p3
Explanation
a 10 Value of a.
p1 1010 Value of p1
p2 1012 Value of p2
p3 1014 Value of p3
3. The operator ‘*’ in pointer concept is also called as “De-reference” Operator Or “Value at Operator“
Example Program
//Handling of pointers in C program
1 #include <stdio.h>
2 void main()
3 {
4 int *pc,c;
5 c=22;
6 printf("Address of c:%d\n",&c);
7 printf("Value of c:%d\n\n",c);
8 pc=&c;
9 printf("Address of pointer pc:%d\n",pc);
10 printf("Content of pointer pc:%d\n\n",*pc);
11 c=11;
12 printf("Address of pointer pc:%d\n",pc);
13 printf("Content of pointer pc:%d\n\n",*pc);
14 *pc=2;
15 printf("Address of c:%d\n",&c);
16 printf("Value of c:%d\n\n",c);
17 }
Output
Address of c: 2686784
Value of c: 22
Address of c: 2686784
Value of c: 2
Explanation of program and figure
1. Code int *pc, p; creates a pointer pc and a variable c. Pointer pc points to some address and that address
has garbage value. Similarly, variable c also has garbage value at this point.
2. Code c=22; makes the value of c equal to 22, i.e., 22 is stored in the memory location of variable c.
3. Code pc=&c; makes pointer pc point to address of c. *pc (value at address pointed by pc) will be equal
to the value of c.
4. Code c=11; makes the value of c as 1. Now Value of *pc will also be 11.
5. Code *pc=2; change the address pointed by pointer pc to change to 2. Since, address of pointer pc is
same as address of c, value of c also changes to 2.
Two possible arithmetic operations in the pointers are addition and subtraction.
Formula : (addition)
New address = current address + added value * size_of(data type)
new address = 1012 + 4*2 variale a p int a=10;
= 1020 value 10 1012
int *p;
p =&a;
address 1012 1014 p = p + 4;
Formula : ( Decrementing)
new address = current address - subtracted value * size_of(data type)
new address = 1012 - 4*2
= 1004
Data Type Older Address stored in pointer Next Address stored in pointer after incrementing (ptr++)
int 1000 1002
float 1000 1004
char 1000 1001
Incrementing a pointer to an integer data will cause its value to be incremented by 2 bytes .
Incrementing a pointer to an float data will cause its value to be incremented by 4 bytes
If we will add or subtract a number from an address result will also be an address.
If we increment a pointer ,it moves to the address of the next element(it moves I byte if it is a character
pointer, 2 bytes if it is an integer pointer and 4 bytes if it is a floating point pointer ).
If we decrement a pointer, it moves to the address of the previous element(it moves I byte if it is a
character pointer, 2 bytes if it is an integer pointer and 4 bytes if it is a floating point pointer ).
Address of ptr[1]
= 1000 + (4 bytes)
= 1004
An array and pointer go hand in hand with each other. An array can be accessed by using pointer. Arrays and
pointers are synonymous in terms of how they use to access memory. But, the important difference between
them is that, a pointer variable can take different addresses as value whereas, in case of array it is fixed.
Example 1
int arr[4];
In arrays of C programming, name of the array always points to the first element of an array. Here, address of
first element of an array is &arr[0].arr represents the address of the pointer where it is pointing. Hence,
&arr[0] is equivalent to arr.
The statement
int arr[1]={10};
is
equivalent to
int *arr;
arr[0]=10;
arr = &a[0];
Similarly,
In C, you can declare an array and can use pointer to access the elements of an array.
Program
//Program to find the sum of six numbers with arrays and pointers.
#include <stdio.h>
void main()
{
int i,class[6],sum=0;
printf("Enter 6 numbers:\n");
for(i=0;i<6;++i)
{
scanf("%d",(class+i)); // (class+i) is equivalent to &class[i]
sum += *(class+i); // *(class+i) is equivalent to class[i]
}
printf("Sum=%d",sum);
}
Output
Enter 6 numbers:
2
3
4
5
3
4
Sum=21
Example 2
int a[5]={10,20,30,40,50};
Value 10 20 30 40 50
Here a[0] is the starting element and the address of a[0] is called the base address
Then Value of a =?
Now what will the variable ‘a’ hold and what will happen when the value of ‘a’ is printed?
printf(“%d”,a);
The output of the statement would be “1010” since an array variable will hold the base address;
int a[5];
something equivalent to the following will happen within the compiler implicitly (i.e. the statements will not be
visible but will happen within the compiler )
Let us see how the elements of the array are accessed using pointer. As we know the array variable ‘a’ is also
considered as pointer and it will hold the variable a[0].
If we increment the array variable a, then it will move to the next element.
It means a[0] = 10
*a or a[0] 10
*(a+1) or a[1] 20
*(a+2) or a[2] 30
*(a+3) or a[3] 40
*(a+4) or a[4] 50
5.2.9 Pointer to Functions (Function Pointer)
A pointer which keeps address of a function is known as Function Pointer.
No function can return more than one value. But using pointers we can return more than one value.
Consider the example below, let us try to return two values at a time
void main()
{
int a=10,b=5;
a,b=square(a,b);//this is meaningless and not supported by c
printf("%d %d",a,b);
}
void square(int j,int k)
{
j=j*j;
k=k*k;
return(j,k);//Error: a function cannot return two values at a time.
}
(Actual (Formal
Variable Parameter) Parameter)
a b j k
Value 10 5 100 25
The above example illustrates that it is not possible to return two values and without returning the values, the
updated values will not be reflected in the main function.
So using pointer, we pass the address of the value and in the called function when the value is updated, it will
directly updating in the memory location and so it will be reflected in the main function.
Example 1
#include <stdio.h>
void main()
{
int a=10,b=5;
square(&a,&b);//the address is passed
printf("%d %d",a,b);
}
void square(int *j,int *k)
{
*j=(*j)*(*j); // updation is done directly in the memory location of variable a.
*b=(*b)*(*b); // updation done directly the memory location of variable b .
}
Variable (actual (ptr variable)
parameter)
a b *j *k
Value 10 5 100 25
Address 1010 1012 1010 1012
Explanation:
&a and j refers to same memory location and hence any updates done using the pointer variable j will
affect the value of a.
&b and k refers to same memory location and hence any updates done using the pointer variable k will
affect the value of b.
Output
100 25
Example 1
In this example, the pointer variable of type struct is referenced to the address of p. Then the structure member
is accessed through pointer using dot operator.
These operators are also used to access data member of structure by using structure’s pointer.
Example 2
#include <stdio.h>
struct book
{
int pages;
float price;
};
void main()
{
struct book *ptr;
struct book p;
ptr=&p; /* Referencing pointer to memory address of p */
printf("Enter no of pages: ");
scanf("%d",&ptr->pages); // (*ptr).pages is equivalent to p.pages
printf("Enter price: ");
scanf("%f",&ptr->price); // (*ptr).price is equivalent to p.price
printf("/nDisplaying:/n ");
printf("%d %f",ptr->pages,*ptr->price);
}
Output:
Enter no of pages:450
Enter price: 220.75
Displaying:
450 220.75
void pointer is a pointer that can store the address of any type of variable
Introduction
Suppose if we have to declare integer pointer, character pointer and float pointer then we need to declare
3 pointer variables.
Instead of declaring different types of pointer variable it is possible to declare single pointer variable
which can act as integer pointer, character pointer or floating point pointer.
Syntax:
void * pointerVaraibleName;
Example :
void *ptr;
char cnum;
int inum;
float fnum;
Explanation:
When we assign address of integer to the void pointer, pointer will become Integer Pointer.
When we assign address of Character Data type to void pointer it will become Character Pointer.
When we assign address of floating point Data type to void pointer it will become floating point
Pointer
A Pointer which does not point to any memory location is called NULL Pointer.
Meaning of NULL
NULL is macro constant which has been defined in the header file stdio.h, alloc.h, mem.h, stddef.h and
stdlib.h as #define NULL 0
Example
int *a;
int *b = NULL;
here ‘*a’ and ‘*b’ are not same because b points to NULL and a may point to some garbage address
Example program:
Void main()
{
int *a;
int *b =NULL;
printf(“value of a =%d \t value of b =%d”,a,b);
}
Output:
NULL is a reserved word in most high-level languages. It is an EXPLICIT value, and not an "undefined"
value.
Example:
#include<stdio.h>
void main()
{
int *p;
printf("%u\n",p);
}
Output:
28618
Here the output is just any random address (Garbage value)
Here p is wild pointer because it has not been initialized. Wild pointer doesn’t point any specific memory
location.
Initially:
Later:
The pointer which can point or access only 64KB data segment of RAM i.e. which can access only 8 segments
is known as far pointer. The size of far pointer is 4 bytes.
Difference between void pointer, NULL pointer, wild pointer and dangling pointer.
It can point to memory It points to a NULL It points to any random It points to a memory
address of any type of value. address(garbage value) address of a variable,
variable. which has been deleted