UNIT 3 PC NOTES

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

UNIT III FUNCTIONS AND POINTERS

Modular programming - Function prototype, function definition, function call, Built- in


functions (string functions, math functions) – Recursion, Binary Search using recursive
functions – Pointers – Pointer operators – Pointer arithmetic – Arrays and pointers – Array of
pointers – Parameter passing: Pass by value, Pass by reference.

3.1 MODULAR PROGRAMMING


Modular programming is defined as a software design technique that focuses ondividing the
program into independent modules.
Each Module contains everything that is needed to execute one aspect offunctionality of the
program.
When we merge one or more modules, it makes up a complete program
Modules are implemented in the program using interfaces.
In C, this is achieved by placing the interface definition in a header file and the
implementation in a source file.
The introduction of Modular programming allowed programmers to use pre- written
code with new applications
Examples of Modular Programming languages : C++, Java
Software using Modular Programming : SAP which comprises of large modules such as
finance, payroll, supply chain , etc

Modular programming

MAIN PROGRAM

FUNCTION 1 FUNCTION 2
FUNCTION n
Modularity can on different levels :
Libraries in Projects
Function in files, etc

Advantages of modular programming


Code is easier to read.
Code is easier to test
Reusability
Easy collaboration between team members
Easy to understand the program.
Debugging and maintenance becomes easy.
Saves programmers time.

Disadvantages of modular programming


o There is a need for extra time and budget for a product in modular programming.
o It is a challenging task to combine all the modules.
o Careful documentation is required so that other program modules are notaffected.
o Some modules may partly repeat the task performed by other modules. Hence, Modular
programs need more memory space.

1
3.2 FUNCTION
A function is a sub program which contains one or more statements to do a particular
task
In C, we can divide a large program into the basic building blocks.
The function contains the set of programming statements enclosed by {}.
A function can be called multiple times to provide reusability and modularity.
In other words, we can say that the collection of functions creates a program.
The function is also known as procedure or subroutine in other programminglanguages.

A function definition contains the four parts as follows


1. Return Data_Type: It defines the data type of the value returned from thefunction. The
return data type can be integer, float, character, etc.
2. Function Name: It defines the name of a function that contains some
parameters.
3. Parameters/ Arguments: Refers to the parameters that are passed to thefunction.
4. Function Body: It is the collection of the statements to be executed for performing the
specific task in a function.

Syntax

return_data_type function_name (argument list )


{
// Statement to be executed in a function;
}

Example
int max (int n1, int n2); // Function name declaration with return data type void main()
{
int a=5,b=10; int
big;
big=max(a,b); // Function call
printf(“the big value is %d “,big)
}
int max (int n1, int n2) // max () is the name of a function
{
int x;
if ( n1 > n2)
x = n1; // return n1 when n1 is greater than n2. else
x = n2; // return n2 when n2 is greater than n1. return
x;
}
Advantage of Using Function

1. Reduce the source code


2. Easy to maintain and modify
3. Easy to debug and to test
4. It can be called anywhere in the program.
5. Concept of modular programming
6. Better Readability
7. Information Hiding

2
3.3 TYPES OF FUNCTIONS
There are two types of functions in C programming
a. Built in functions or Library Functions: Functions such as scanf(), printf(),gets(),etc
b. User-defined functions: Functions are created by the C programmer
a) BUILT-IN FUNCTION OR LIBRARY FUNCTIONS
 Library functions are built-in functions that are grouped together and placed in a common
location called library.
 Each function here performs a specific operation.
 We can use this library functions to get the pre-defined output.
 All C standard library functions are declared by using many header files.
 These library functions are created at the time of designing the compilers.
 We include the header files in our C program by using #include<filename.h>.
 Whenever the program is run and executed, the related files are included in theC program.
Math functions
Functions
S.No (Syntax) Meaning Example
1 sqrt(x) Returns the squareroot of x (√x) sqrt(25)
2 log(x) Logex log(75)
3 abs(x) |x | abs(-5)
4 fabs(x) |x | fabs(4.65)
5 exp(x) E x exp(5.3)
6 pow(x, y) Xy pow(3, 2)
7 ceil(x) Rounding x to the next biggest integer value ceil(5.6)
8 floor(x) used to convert a floating point number to its floor(5.6)
immediately smaller integer
9 fmod(x, y) Returns the remainder of x/y fmod(7,3)
11 rand( ) Generates a positive random number rand( )
12 sin(x) sin value of x sin(30)
13 cos(x) cos value of x cos(60)
14 tan(x) tan value of x tan(90)
15 cbrt(x) Returns the cube root of x

String functions
S.N Function & Purpose
1) strlen(string_name) returns the length of string name. Ex:
strlen(“Welcome”)
output : 7
2) strcpy(destination, source) copies the contents of source string todestination string.
Ex: strcpy(s1,”welcome”)
output: s1=welcome
3) strcat(first_string, second_string) concats or joins first string with second string. The result
of the string is stored in first string.
Ex: strcat(“Wel”,”come”) output:
Welcome
4) strcmp(first_string, second_string) compares the first string with second string. If both
strings are same, it returns 0.
Ex:strcmp(“Welcome”,”Welcome”)output: 0

3
5) strrev(string) returns reverse string. Ex.
strrev(“Welcome”)
output: emocleW
6) strlwr(string) returns string characters in lowercase. Ex.
strlwr(“Welcome”)
output: welcome
7) strupr(string) returns string characters in uppercase. Ex.
strlwr(“Welcome”)
output: WELCOME

b. USER DEFINED FUNCTIONS


User defined functions are subprograms that contains one or more statements to do a
particular task. These are defined by the programmer.

Advantages of user defined functions (Need for User defined functions)


 To avoid duplication of code in the programs by using functions.
 Code can be written more quickly and be more readable as a result.
 Code can be divided and conquered using functions. This process is known asDivide and
Conquer.
 One task can be divided into several smaller sub-tasks by using functions, thus
 reduces the overall complexity.
 Functions developed in one program can be used in another which reduces thedevelopment
time.

3.4 Elements of user defined Function [Aspects or Parts of UDF]


1 Function declaration / Function prototype : A function declaration or a function prototype tells
the compiler about the function name, return type and parameters. It should be declared in the main
program

Syntax: return_Type function_Name(dt parameter1, dt parameter2, .............................. );


where ,
 return type of a function can be char, int, float, etc
 function name are identifiers.
 dt is the data type of the parameters
 Parameters are the values passed to function.
Example int add(int x, int y);
int – return type add–
function_name
int x, int y – arguments or variables of types int

2 Function definition : The function definition consists of a function header followed by the body
of the function
Syntax
return_Type function_name(dt parameter_1, dt parameter_2, .......................... )
{
Statements / Body of the function
}
3. Function call: The calling statement consists of function name with the parameters Syntax:
function_name(argument_list);

Example: Here is an example to find the sum of two numbers. a user-defined function add() is created
to perform this task
#include <stdio.h>
4
int add(int x,int y); //function declaration
int main()
{
int i,j,sum;
printf("Please enter 2 numbers for find sum\n");
sum=add(i,j); //function call
scanf("%d %d",&i,&j);
printf("The result of sum is :%d",sum);
return 0;
getch();
}
int add(int x, int y) //function definition
{
int result;
result=x+y;
return result;
}

3. 5 Difference between Library function and User defined function

S. Library Function User Defined function


No
1 Library functions are pre
defined User defined functions are the function
functions which are created by the user as per their
own requirements
2 Written in separate header file Written in the program or own header file
3 Function name is given by Function name is decided by user
developers
4 Name of the functions cannot be Name of the functions can be changed at any
changed time
5 Example: sin(), cos(), power() Example: fibo(), add(), cube(), fn1()

3.6 CALLING FUNCTION (or) FUNCTION CALL STATEMENT

 A function call is an important part of the C programming language.


 It is only called by its name in the main() function of a program.
 We can pass the parameters to a function calling in the main() function.

Syntax
function_name();
(or)
function_name(parameter types);
(or)
var_name= function_name();(or)
var_name= function_name(parameters)

Example for a function call


void abc(int,int);
void main() // Calling function
{
; ;
abc(x,y); // Function call - x, y are actual arguments
}
5
abc(int l, int K) // Function Definition - l, k are formal or dummy arguments
{
return(); //return statement
}
Terms related with function :
 Actual arguments: The arguments in function call are called actual arguments.
 Dummy arguments: The arguments in function definition are called dummyarguments.
 Function Name: The name given to the function.
 Argument/Parameter List: The variable name enclosed within the parenthesis in function
definition
 Function call: Calling the function
 Variables: There are two kinds of variables. They are 1. Local and 2. Global.
o Local variables: The variables that are declared inside the function
o Global Variables : Variables that are declared outside the main function
 Return value: The result obtained by the function is sent back by the function to the function
call through the return statement. It returns one value only

3.7 TYPES OF USER DEFINED FUNCTIONS


 It is based on number of arguments a function accepts and the return value
 The Function prototypes are classified into four types.
 They are :
1. Function with no argument and no return value.
2. Function with no argument and with return value.
3. Function with argument and no return value.
4. Function with argument and with return value.
1 Function with no argument and no return value
 A function that does not take any arguments and does not return a value . This is also called a
void function
 There is no data transfer between calling and the called function.
 The function is only executed and nothing is obtained.
 The Function acts independently.
 It reads data values and print result in the same block.
Syntax:
void function()
{
…..
}
Eg: Function with no argument and no return value
/* program to calculate the area of square */
#include <stdio.h>
void area(); //function prototype
int main()
{
area(); //function call
return 0;
}
void area(){
int a,side;
printf("Enter the side of square :"); //Function definition
scanf("%d",&side);
a = side * side;
printf("Area of Square = %d",a);
}
6
2 Function with no argument and with return value
Function with no arguments means called function does not receive any data from calling function
and function with return value means result will be sent back tothe caller from the function.
 The called function is independent. It reads values from the keyboard and returns value to the
function call.
 Here both the called and calling functions partly communicate with each other.
Syntax
returntype function()
{
……
return(value);
}
Eg : Function with no argument and with return value
#include <stdio.h>
int area(); //function prototype with return type int
int main()
{
int a;
a = area(); //function call
printf("Area of Square = %d",a);
return 0;
}
int area(){
int a,side;
printf("Enter the side of square :");
scanf("%d",&side);
a = side * side;return a;
}
3. Function with argument and no return value
 Here function will accept data from the calling function as there are arguments, however, since
there is no return type nothing will be returned to the calling program. So it’s a one-way type
communication.
 The functions are partly dependent on the calling function.
 The result obtained is utilized by the called function.
Syntax
void function(arguments)
{
…..
}
Eg : Function with argument and no return value
#include <stdio.h>
void area( int side); //function prototype
int main(){
int side;
printf("Enter the side of square :");
scanf("%d",&side);
area(side); //function call
return 0;
}
void area(int side){
int a;
a = side * side;
printf("Area of Square = %d",a);
7
}
4. Function with argument and with return value
 Function with arguments and with return value means both the calling function and called
function will receive data from each other.
 It’s like a dual communication.
Syntax
returntype function(arguments)
{
… return(value)
}

Eg. Function with argument and with return value


#include <stdio.h>
int area(int side); //function prototype with return type int
int main()
{
int a,side;
printf("Enter the side of square :");
scanf("%d",&side);
a = area(side); //function call
printf("Area of Square = %d",a);
return 0;
}
int area(int side)
{
int a;
a = side * side;
return a;
}

3.8 RECURSION
 The process of calling the function by itself again and again until some condition is
satisfied is called recursive function.
 Recursive programs must have at least one if statement to terminate recursion,
otherwise infinite loop will be created.
 Each recursive call is made with a new, independent set of arguments
 Allows very simple solution for very complex problems
 Recursive solution consists of two cases:
o base case : Base case is the smallest instance of problem, which can be easily solved
and there is no need to further express the problem in terms of itself. For example, in
factorial of a number, base case is if n==1, fact=1.
o recursive case: The problem is defined in terms of itself, while reducingthe problem
size. For example, when fact(n) is expressed as n* fact(n-1), the size of the problem is
reduced from n to n-1.

Advantages of recursion
 Recursive functions make the code look clean and elegant with less no. ofstatements
 A complex task can be broken down into simpler sub-problems using recursion.
 Useful for branching processes

Disadvantages of recursion
 Sometimes the logic behind recursion is hard to follow through.
 Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
8
 Recursive functions are hard to debug.

Expressing recursion in the form of base cases and recursive cases.


fact(n)=
Recursive method for factorial is evaluated as 1!=1
2!=2 * 1=2 * 1!
3!=3 * 2 * 1=3 * 2!
4! = 4 * 3 * 2 * 1 = 4 * 3!
Program :
#include<stdio.h>
int fact(int );
void main()
{
int n,factorial;
printf(“Enter a number:”);
scanf(“%d”,&n);
factorial=fact(n);
printf(“\nFactorial of %d is %d”,n,factorial);
}
int fact(int n){
if (n <= 1)
return 1;
else
return n * fact (n-1);
}
Output: Enter a number: 5
Factorial of 5 is 120
Practice programs
1. Write a C Program to find the Power of a Number using Recursion
2. Write a C Program to find the Sum of Digits of a Number using Recursion
3. Write a C program to create Scientific calculator using built-in functions

3.9 BINARY SEARCH USING RECURSIVE FUNCTION


 Binary Search is a search algorithm that is used to find the position of an element
(target value) in a sorted array.
 The array should be sorted prior to applying a binary search.
 The binary search algorithm works by comparing the element to be searched by the middle
element of the array and based on this comparison follows the required procedure.
 Case 1 − element = middle, the element is found return the index.
 Case 2 − element > middle, search for the element in the sub-array starting from
middle+1 index to n.
 Case 3 − element < middle, search for element in the sub-array starting from 0 index to
middle -1.
// Program for Recursive implementation of Binary search
#include <stdio.h>
int b_search(int num[], int Left, int Right, int key)
{
int Middle = 0;
while (Left <= Right) {
Middle = (Left + Right) / 2;
if (num[Middle] == key)
return Middle;

9
if (num[Middle] > key)
return b_search(num, Left, Middle-1, key);
else
return b_search(num, Middle+1, Right, key);
}
return -1; // If the element is not found
}
int main(){
int size = 0, key = 0, found = 0;
printf("Enter the size of the array: ");
scanf("%d", & size);
int num[size];
printf("Enter the elements of the array in ascending order: ");
for (int i = 0; i < size; i++) {
scanf("%d", & num[i]);
}
printf("Enter the element to be searched: ");
scanf("%d", & key);
found = b_search(num, 0, size - 1, key);
if (found == -1)
printf("Element is not present in the array");
else
printf("Element found at index %d", found);
return 0;
}
Output :
Enter the size of the array: 6
Enter the elements of the array in ascending order: 2 3 4 5 6 7
Enter the element to be searched: 3
Element found at index 1

3.10 POINTERS
 A pointer is a variable that stores the memory address of another variable.
 A pointer variable has the data type of the data it is pointing to. It is created with the *
operator. ie if the pointer has the address of an integer value, the data type of pointer is also int.
 The address of the variable is assigned to the pointer.
 A pointer can be incremented/decremented, i.e., to point to the next/ previous memory
location.
 The purpose of pointer is to save memory space and achieve faster execution time. For
example
 Declaration of Pointer:
Syntax: data type *ptr_var;
Ex. int *ip;
float *fp;
 Inititalization of pointers :
In pointers, initialization is done by assigning the address of a variable to a pointer
variable. This is achieved by ampersand ‘&’ operator. This is called address of
operator
Syntax : data_type * ptr, var;
ptr = &var;
Example : int *p, a;
p = &a;
Using pointer p, we can assess the content of variable a
10
 Pointers to pointers
Pointer variable contains the address of another variable. Another pointer variable can store
the address of a pointer variable. This variable is called pointer topointer
Syntax = data type **ptr_var;
Example : int **p;

Example:
#include<stdio.h>
void main()
{
int a=5, *p1, *p2;
p1=&a;
p2 = &p1;
printf(“Direct Access, a=%d\n”,a);
printf(“Indirect Access through pointer p1, a=%d\n”,*p1); printf(“Indirect Access
through pointer p2, a=%d\n”,**p2);
}
Output

11
Direct Access a =5
Indirect Access through pointer p1, a =5
Indirect Access through pointer p2, a =5

 Every pointer variable takes the same amount of memory space irrespective of whether
it is a pointer to int, float, char, or any other type

3.11 POINTER OPERATORS


1. Address of Operator: The address of operator ( & ) is a unary operator that returns the address of
its operand. Its operand can be a variable, function, array, structure, etc.
Syntax: &variable_name;
2. Dereferencing Operator: The dereference operator ( * ), also known as the indirection operator.
When indirection operator (*) is used with the pointer variable, then it is known as dereferencing a
pointer. When we dereference a pointer, then the value of the variable pointed by this pointer will be
returned.
Features / Advantages of Pointers :
 Pointers reduce the length and complexity of the programs
 Pointers are efficient in handling data
 Pointers enable us to access the memory directly
 Pointers saves memory space
 Two dimensional and multidimensional array representation is easy in pointers
 Pointers provide an alternate way to access an array element

3.12 POINTER ARITHMETIC


 Arithmetic operations can be applied to pointers in a restricted form. When
arithmetic operators are applied on pointers, the outcome of the operation is governed
by pointer arithmetic.
 The pointer arithmetic operations are listed below:
1. Increment/Decrement of a Pointer
2. Addition of Integer to Pointer
3. Subtraction of Integer to Pointer
4. Subtraction of Two Pointers
5. Comparison of pointers of the same type

1. Increment/Decrement of a Pointer
Increment operation of a pointer : It is a condition that also comes under addition. When a pointer
is incremented, it actually increments by the number equal to the size of the data type for which it is
a pointer.
For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by
4(size of an int), for a 32 bit computer and the new address will pointto 1004.
Decrement operation of a pointer : It is a condition that also comes under subtraction. When a
pointer is decremented, it actually decrements by the number equal to the size of the data type for
which it is a pointer.
For Example: If an integer pointer that stores address 1000 is decremented, then it will decrement
by 4(size of an int), and the new address will point to 996.
Note : pointers are incremented and decremented by the size of the data typethey point to
// pointer Increment / decrement operation
#include <stdio.h>
int main()
{
int a = 2; int
*p = &a;
printf("p = %u\n", p);

12
p++;
printf("p++ = %u\n", p); // +4 bytes for 32 bit integers
p--;
printf("p-- = %u\n", p); // -4 bytes
return 0;
}
Sample output
p = 3620
p++ = 3624
p-- = 3620

2. Addition of Integer to Pointer


When a pointer is added with an integer value, the value is first multiplied by the size ofthe data type
and then added to the pointer.
For Example : Suppose the ptr is an integer pointer that stores 1000 as an address. Ifwe add integer 5
to it using the expression, ptr = ptr + 5, then, the final address stored in the ptr will be ptr = 1000 +
sizeof(int) * 5 = 1020.
Example Program :
#include<stdio.h>
void main()
{
int a=10;
int *ptr;
ptr=&a;
printf("Value of ptr : %u",ptr);
ptr=ptr+3;
printf("\nNew Value of ptr : %u",ptr);
}
Sample output :
Value of ptr : 7172
New Value of ptr : 7184

3. Subtraction of Integer to Pointer


When a pointer is subtracted with an integer value, the value is first multiplied by the size of the data
type and then subtracted from the pointer similar to an addition.
For Example: Suppose, ptr is an integer pointer that stores 1000 as an address. If we subtract
integer 5 from it using the expression, ptr = ptr – 5, then, the final address stored in the ptr will be
ptr = 1000 – sizeof(int) * 5 = 980.
// C program to illustrate pointer Subtraction
#include <stdio.h>
int main()
{
int N = 4;
int *ptr1;
ptr1 = &N;
printf("Pointer ptr1 before Subtraction: %u ", ptr1);
ptr1 = ptr1 - 2;
printf("\nPointer ptr1 after Subtraction: %u ",ptr1);
return 0;
}
Sample output
Pointer ptr1 before Subtraction: 1108
Pointer ptr1 after Subtraction: 1100

13
4. Subtraction of Two Pointers
The subtraction of two pointers is possible only when they have the same data type. The result is
generated by calculating the difference between the addresses of the two pointers and dividing by
the size of the data type.
For Example: Two integer pointers say ptr1(address:1000) and ptr2(address:1004) are
subtracted. The difference between addresses is 4 bytes. Since the size of int is 4 bytes, therefore the
difference between ptr2 and ptr1 is given by (4/4) = 1.
//Example of Subtraction of Two Pointer
#include <stdio.h> int
main()
{
int x = 6; // Integer variable declaration
int N = 4;
int *ptr1, *ptr2;
ptr1 = &N; // stores address of N
ptr2 = &x; // stores address of x
printf(" ptr1 = %u, ptr2 = %u \n", ptr1, ptr2);
x = ptr2 – ptr1;
printf("Subtraction of ptr2 & ptr1 is %d\n", x);
return 0;
}
Sample output:
ptr1 = 1016, ptr2 = 1020
Subtraction of ptr2 & ptr1 is 1

5. Comparison of pointers of the same type


We can compare the two pointers by using the comparison operators in C. We can implement this by
using all operators in C >, >=, <, <=, ==, !=. It returns true for the validcondition and returns false for the
unsatisfied condition.
#include <stdio.h>
int main()
{
int a=300,b=200;
int *p1,*p2,*p3;
p1 = &a;
p2 = &b;
p3 = &a;
printf("%u \t %u \t %u\n",p1,p2,p3);
if(p1 > p2)
{ printf("P1 is greater than p2");}
else
{printf("P2 is lesser than p1"); }

if (p2==p3)
printf("\n They point to same variable");
else
printf("\n They point to different variable");
return(0);
}
Output:
7012 7008 7012
p1 is greater than p2
They point to different variable

14
Illegal pointer operations:
1 Addition of two pointers are not allowed
2 Only integers can be added to pointer. It is not valid to add a float or a double valueto a pointer
3 Multiplication and division operators cannot be applied on pointers. 4
Bitwise operators cannot be applied on pointers.
5 A pointer variable cannot be assigned a non-address value (except Zero)

3.13 POINTERS AND ARRAYS


a. Pointer to an Array:
 Arrays and Pointers have close relationship. The name of the array itself is a pointer
which always points to the first element of the array.
 For an array, consecutive memory locations are allocated for array elements. So array
elements can be easily assessed using pointers.
 It is possible to create a pointer that points to a complete array Such a pointer is known as a
pointer to an array.
Example :
#include<stdio.h>
void main()
{
int a[5] = {1,2,3,4,5};
int *ptr,i;
ptr = a; // same as p = &a[0]
for (i = 0; i < 5; i++)
printf("%d\t", *(ptr + i));
}
Output : 1 2 3 4 5
Explanation : In the above example, ptr has the starting address of a ie a[0]. So &a[0] is equivalent to
(ptr+0) and hence the value in a[0] is equivalent to *(ptr+0). Similarly, &a[1] is equivalent to (ptr+1)
and hence a[1] is equivalent to *(ptr+1) and so on .

b. Pointer to Two Dimensional array


Memory allocation for a two-dimensional array is as follows :
int a[3] [3] = {1,2,3,4,5,6,7,8,9};

int *p ;
p=a or p =&a[0][0] assigning base address to the pointer
Pointer can be used to access the elements of 2 dimensional array using thefollowing formula:
a[i][j] = *(p + i x col_size + j)
Example:
To find value in a[1] [2], following steps are carried out :
= *(1234 + 1*3+2) // 1234 is the pointer value ie &a[0][0]
= *(1234 + 3+2)
= *(1234 + 5*4) // 4 is Scale factor

15
// Program for pointer to two dimensional array
#include<stdio.h>
void main ( )
{
int a[3][3]={1,2,3,4,5,6,7,8,9};
int i,j;
int *p;
p = &a[0][0];
printf ("elements of 2d array are \n");
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
printf ("%d ", *(p+i*3+j));
}
printf ("\n ");
} }

Output:

16
elements of 2d array are 1
2 3
4 5 6
7 8 9

c. Array of Pointers:
An array of pointers is a collection of addresses.
The addresses in the array of pointers could be the addresses of different variables
All the pointers in an array must be of the same data type.

Example program
#include<stdio.h>
void main()
{
int a=10, b=20, c=30;
int* arr[3];
arr[0]=&a; arr[1]=&b;
arr[2]=&c;
printf("The values of variables are:\n");
printf("%d\t%d\t%d",a,b,c);
printf("\n the pointer variable values are %d\t%d\t%d\n",*arr[0],*arr[1],*arr[2]);
printf("\n the address are %u\t%u\t%u\n",arr[0],arr[1],arr[2]);
}
Output
The values of variables are 10 20 30
the pointer variable values are 10 20 30
the address are 4000 4400 5400

Explanation:
arr is an array of integer pointers and holds the addresses of variables a, b and c
All the variables are of the same type.

Example 2:
#include<stdio.h>
void main ( )
{
int a[3]={10,20,30};
int i,*ptr[3];
for(i=0;i<3;i++)
ptr[i]=&a[i];
printf("Values in array = ");
for (i=0;i<3;i++)
printf(" %d \t",*ptr[i]);
}
Output:
Values in array = 10 20 30
3.14 Void pointer and Null Pointer
Void Pointer : A void pointer is the one who does not have any data type with it. It is also called as a
general purpose pointer. It can hold the addresses of any data type
17
Syntax :
void *<ptr_name>;
Example :
void *p;
int a; char c;
p = &a; //p changes to integer pointer as address of integer is assigned to it
p = &c; //p changes to character pointer as address of character is assigned to it

Null Pointer : A pointer that is assigned a NULL is called NULL pointer. It is a good practice to
assign a NULL to a pointer if it does not have an exact address to be assigned.
Syntax :
<data type> *ptr = NULL;
Eg :
# include <stdio.h> int
main()
{
int *p = NULL;
printf(“The value of pointer p is %u \n”,p);return
0;
}
Output :
The value of pointer p is 0
The difference between NULL pointer and void pointer is that NULL pointer is a value and
void pointer is a type
3.15 Pointer for strings
Strings are character arrays terminated by null character. Pointer to a single string may be declared in
the same way as the pointer to a one-dimensional array.
char Name[] = “AAA”; char
*ptrname ; ptrname = Name;

Though the declaration and initialization of a pointer to a string is similar to that of a pointer to an
array, the difference lies in the input/output. String may be taken as a single object for input and
output and its characters may also be treated like elements of an array.
// Program to Illustrate pointer to strings
#include <stdio.h>
#include<conio.h>
void main()
{
char *cities[] = {"Chennai", "Delhi","Mumbai"};int i;
clrscr();
for(i = 0; i < 3; i++)
printf("%s\n", cities[i]);
getch();
}

Output :
Chennai
Delhi
Mumbai

Note :Pointers are very helpful in handling character array with rows of varying lengthFor Eg :
Char *name[2] = {“Ram”,”Seetha Raman”, }; will
occupy lesser space than
char name[2][15] = {“Ram”,”Seetha Raman”, };
18
3.16 Function Pointer in C (or) Pointer to Function
In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a
simple example that shows declaration and function call using function pointer.
#include <stdio.h>
void fun(int a) // A normal function with an int parameter and void return type
{
printf("Value of a is %d\n", a);
}
int main(){
void (*fun_ptr)(int);
fun_ptr = &fun;
(*fun_ptr)(10); // Calling fun() using fun_ptr
return 0;
}
Output:
Value of a is 10
Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer
stores the start of executable code.

3.17 PARAMETER PASSING: PASS BY VALUE, PASS BY REFERENCE.


Call by value (or) Pass by value (or) Passing Arguments by value:
In this method, values of actual arguments are copied to the formal parameters ofthe function.
If the arguments are passed by value, the changes made in the values of formal parameters
inside the called function are not reflected back to the calling function

Example Program:

#include<stdio.h>
void swap(int,int);
void main()
{ int a,b;
printf("Enter a and b values:");
scanf("%d %d",&a,&b);
printf("Before swap(), a=%d\tb=%d\n",a,b);
swap(a,b);
printf("\nAfter swap(), a=%d\tb=%d\n",a,b);
}
void swap(int x,int y){
int temp;
temp=x;
x=y;
y=temp;
printf("\In swap() function, x=%d\t y=%d",x,y);
}
OUTPUT:
Enter a and b
values: 10 20
Before swap(),
a=10 b=20
In swap() function
x=20 y=10
After swap(),
a=10 b=20
19
Call by Reference (or) Pass by reference(or) Passing Arguments by reference:

In this method, the addresses of the actual arguments are passed to the formal parameters
of the function. If the arguments are passed by reference , the changes made in the values pointed
to by the formal parameters in the called function are reflected back to the calling function

Example Program:

#include<stdio.h> void
swap(int*,int*); void
main()
{
int a,b;
printf("Enter a and b values:");
scanf("%d %d",&a,&b);
printf("Before swap(), a=%d\tb=%d\n",a,b);
swap(&a,&b);
printf("\nAfter swap(), a=%d\tb=%d\n",a,b);
}
void swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
printf("\In swap() function, x=%d\t y=%d",*x,*y);
}
OUTPUT:
Enter a and b values: 10 20
Before swap(), a=10 b=20 In
swap(), x=20 y=10
After swap(), a=20 b=10

Comparison between Call by Value and Call by reference

S.No Call by Value Call by Reference


1 The values of the actual parameters The values of the actual parameters do
do not change by changing the formal change by changing the formal
parameters. parameters.
2 Copy of the values are passed to the The address of the values are passed to the
function function
3 A change made inside the function is A Change made inside the function
limited to the function only. validate outside of the function also.
4 Actual and formal arguments are created Actual and formal arguments are created at the
at the different memory location same memory location

5 New location is created , this Existing memory location is used through its
method is slow address, this method is fast

20
//Additional Programs
//To find Sum of N natural numbers Using Function
#include<stdio.h>
#include<conio.h>
void sum();
void main()
{
clrscr();
sum();
getch();
}
void sum()
{
int i,sum1=0,num;
printf("Enter a number:");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
sum1=sum1 + i;
}
printf("Sum of Natural Number is %d",sum1);
}

//To find the maximum of 3 numbers using parameter passing


#include<stdio.h>
#include<conio.h>
int max(int,int,int);
void main()
{
int x,y,z,big;
clrscr();
printf("Enter x,y and z values:");
scanf("%d%d%d",&x,&y,&z);
big=max(x,y,z);
printf(“\nMaximum = %d”,big);
getch();
}
int max(int a, int b, int c)
{
if(a>b && a>c)
return(a);
else if(b>a && b>c))
return(b);
else
return(c);
}

21
// C program using pointer to read in an array of integers and print its element in reverse order
#include<stdio.h>
#include<conio.h>
void main()
{
int size, i, arr[10];
int *ptr;
clrscr();
ptr = &arr[0];
printf("\nEnter the size of array : ");
scanf("%d", &size);
printf("\nEnter %d integers into array: ", size);
for (i = 0; i < size; i++)
{
scanf("%d", ptr);
ptr++;
}
ptr = &arr[size - 1];
printf("\nElements of array in reverse order are :");
for (i = size - 1; i >= 0; i--)
{
printf("\nElement%d is %d : ", i, *ptr);
ptr--;
}
getch();
}

/*string operations using pointers and without string library functions */


#include<stdio.h>
#include<conio.h>
void slen(char *s);
void scpy(char *s,char *ss);
void scmp(char *s,char *ss);
void scat(char *s,char *ss);
void srev(char *s);
void main()
{
char s1[100],s2[100],s3[100],s4[100];
clrscr();
printf("\n Enter string1:");
gets(s1);
slen(s1);
srev(s1);
printf("\n Enter string2:");
gets(s2);
scpy(s3,s2);
printf("\n Enter the another for strcmp() and strcat() with s2:");gets(s4);
scmp(s2,s4);
scat(s2,s4);
getch();
}

22
void slen(char *s) //String Length
{
int l;
for(l=0;s[l]!='\0';l++);
printf("\nLength of string (%s) is %d\n",s,l);
}
void srev(char *s) //String Reverse
{
int i,j;
char temp;
for(i=0;s[i]!='\0';i++);
i--;
for(j=0;i>j;)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
j++;
i--;
}
printf("\nThe reversed string is %s \n",s);
}
void scpy(char *s, char *ss) //String Copy
{
int i;
for(i=0;ss[i]!='\0';i++)s[i]=ss[i];
s[i]='\0';
printf("\nString copy from s2 to s3 is %s\n",s);
}
void scmp(char *s, char *ss) //String Compare
{
int flag,i;
for(i=0;s[i]!='\0'||ss[i]!='\0';i++)
{
if(s[i]==ss[i])
flag=1;
else
{
flag=0;
break;}
}
if(flag==1)
printf("\n Two strings are equal\n");
else
printf("\n Two strings are not equal");
}
void scat(char *s, char *ss) //String Concatenation
{
int i,j;
for(i=0;s[i]!='\0';i++);
for(j=0;ss[j]!='\0';j++)
{
s[i]=ss[j];
i++;
23
}
s[i]='\0';
printf("\n The concatenate(s2,s4) is %s\n",s);
}
IMPORTANT QUESTIONS – UNIT 3
Questions
1. Define pointer. How will you declare it?
2. What is a pointer to a pointer?
3. Express the operations that can be performed on pointers.
4. What is pointer arithmetic? What are valid pointer arithmetic operations?
5. What are a void pointer and a null pointer?
6. Differentiate between address operator and indirection operator?
7. Why is pointer arithmetic not applicable on void pointers?
8. Which is better to use? Macro or function. Justify your answer.
9. What is the relation between the operators '&' and '*' in C pointers?
10 Identify the use of Pointer.
11 Point out the meaning of user-defined function.
12 What is meant by library function?
13 Write the syntax for function declaration.
14 Compose the two parts of function definition.
What is the output of the following code fragment? int x=
456, *p1, *p2;
15 p1=&x; p2=&p1;
printf ("Value of x is : %d\n", x);
printf("Value of *p1 is : %d\n", *p1);
printf ("Value of *p2 is: %d\n", *p2);
16 When null pointer is used?
17 What is meant by pass by value and pass by reference?
18 What is a function call? Give an example of a function call.
19 Invent the meaning of default arguments and command line arguments.
20 What is a recursive function?
21 Specify the need for function.
22 Assess the meaning of function pointer.
23 What is array of pointer?
24 Mention the advantage of pass by reference.
25 Compare actual parameter & formal argument
26 What is a function? What are its uses?
27 List out any 4 math functions

24
28 What is a function prototype?
29 Differentiate library and user defined functions
30 Differentiate call by value and call by reference
PART – B
1. Describe about pointers and their operations that can be performed on it.
2. What is modular Programming? How does the Language C support modular
programming? Explain in detail.
3. What is an array of pointers and what is pointer to an array? Explain in detail with
example.
4. Explain about pointers and write the use of pointers in arrays with suitable example.
5. Demonstrate about function declaration and function definition.
6. Classify the function prototypes with suitable examples.
7. What is the necessity of parameter passing in C Programs? What are the two types ofdoing that?
Explain any one in detail.
8. Discuss about the classification of functions depending upon their inputs and output
(parameters)
9. Explain in detail about Pass by Value and Pass by reference.
10 Discuss about passing arrays to function.
11 Explain in detail about recursive function with sample code.
12 Explain in detail about function pointers.
13 Write notes on fixed argument functions and variable argument functions.
14 What are the applications of recursive function? Computation of Sine series using C
program.
15 Write a C program for Scientific calculator using built-in functions.
16 Write a C program for Swapping of two numbers and changing the value of a variable using
pass by reference.
17 Write a C program to sort the given N names.
18 Explain any eight build in functions of math.
19 What is recursion? Explain the procedure to compute sin(x) using recursive functions. Write the
C code for the same.
20 Write a C program to reverse a string using recursion.
21 What is a function in C? Explain the steps in writing a function in C program withExample

22 What is recursion? Write a C program to find the sum of the digits, to find the factorial of a
number and binary search using recursion.
23 Explain the various pointer arithmetic operations with example
24 Explain array of pointers with example
25 Discuss about Pointer operators in brief

25

You might also like