0% found this document useful (0 votes)
14 views

Unit-1 - Data Structures Using C

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Unit-1 - Data Structures Using C

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Data Structures using C Unit - I

ELEMENTARY DATA ORGANIZATION


Attributes: Regno Name DOB Address

Values: 25 May 55 Railway Colony, Dharmapuri Dt., Pincode


26501245 Ravi
1982 - 636701

Data Data are simply values or set of values. Regno, Name, DOB, Address.

Data Item A single unit of values. Regno, Name.

Group Item Data items that are divided into sub-items are called group items. (Not an elementary
items). DOB, Address
Entity An entity is something that has certain attributes or properties which may be
assigned values. Person, Place, organizations.
Attributes Each entity has a set of properties. The attributes can have numeric of alphanumeric
values. Regno, Name, DOB, Address.
Entity Set Entities with similar attributes form an entity set. All the employees in an organization

Information Data with given attributes, or meaningful or processed data.

Field A field is a single elementary unit of information representing an attribute of an entity.

Record A record is the collection of field values of the given entity.

Fixed–Length All the records contain the same data items with the same amount of space assigned
Records to each data item.
Variable- File records may contain different lengths.
Length Record
File A file is the collection of records of the entities in a given entity set.

DATA STRUCTURES
The study of the data structures, which form the subject matter of this text, includes the following
three steps:

1. Logical or mathematical description of the structure.


2. Implementation of the structure on a computer.
3. Quantitative analysis of the structure (to determine amount of memory needed to store
and time to process the structure).

Data structure is the logical or mathematical model of a particular organization of data.

1
Data Structures using C Unit - I

TYPES OF DATA STRUCTURES

DATA STRUCTURES

Primitive data Non-primitives data


structures structures

integer Linear Data Non-linear Data


Structures structures

real Arrays Trees

character Graphs
Linked List

Boolean Stack

Queue

Primitive Basic data types; cannot be divided.


data structures Such as integer, real, character and Boolean.

Non - Primitive The processing of complex numbers.


data structures Example: array, linked list, stacks, queues, trees and graphs.

Linear If its elements form a sequence or a linear list.


data structures Example: array, linked list, stacks, queues.

Non – linear If the data is not arranged in sequence.


data structures Example: trees and graphs.

DIFFERENT APPROACHES TO DESIGNING AN ALGORITHM


A complex system may be divided into smaller units called module.

Advantage of modularity:

 When dealing with detail of each module in isolation (ignoring details of other modules).

 When dealing with overall characteristics of all modules and their relationships in order to
integrate them into the system.

 Modularity enhances design clarity which in turn eases implementation, debugging,


testing, documenting, and maintenance of the product.

A system consists of components, which have components of their own. Indeed a system is a
hierarchy of components. The highest level component corresponds to the total system. To
design such hierarchies there are two possible approaches;

2
Data Structures using C Unit - I

1. Top-down approach

2. Bottom-up approach

TOP-DOWN APPROACH

 Top-down design method takes the form of step-wise refinement;

 Start with the topmost module and incrementally add modules that it calls.

 In each step, design is refined into most concrete level until we reach the level where no
more refinement is needed and the design can be implemented directly.

BOTTOM-UP APPROACH

 Bottom-up method works with layers of abstraction.

 Starting from the very bottom, the operations that provide a layer of abstraction are
implemented.

 The operations of this layer are then used to implement more powerful operations and
still higher layer of abstraction, until the stage is reached where the operations supported
by the layer are those desired by the system.

COMPLEXITY
SPACE COMPLEXITY

When we design an algorithm to solve a problem, it needs some computer memory to complete
its execution. For any algorithm, memory is required for the following purposes...

1. Memory required to store program instructions

2. Memory required to store constant values

3. Memory required to store variable values

4. And for few other things

Space complexity of an algorithm can be defined as follows...

Total amount of computer memory required by an algorithm to complete its execution is


called as space complexity of that algorithm

Generally, when a program is under execution it uses the computer memory for THREE reasons.
They are as follows...

1. Instruction Space: It is the amount of memory used to store compiled version of


instructions.

2. Environmental Stack: It is the amount of memory used to store information of partially


executed functions at the time of function call.

3. Data Space: It is the amount of memory used to store all the variables and constants.

3
Data Structures using C Unit - I

To calculate the space complexity, we must know the memory required to store different data
type values (according to the compiler). For example, the C Programming Language compiler
requires the following...

1. 2 bytes to store Integer value,

2. 4 bytes to store Floating Point value,

3. 1 byte to store Character value,

4. 6 (OR) 8 bytes to store double value


Example 1: Consider the following piece of code...

int square(int a)

return a*a;

In above piece of code, it requires 2 bytes of memory to store variable 'a' and another 2 bytes of
memory is used for return value.

That means, totally it requires 4 bytes of memory to complete its execution.

If any algorithm requires a fixed amount of space for all input values then that space
complexity is said to be Constant Space Complexity

Example 2: Consider the following piece of code...

int sumOfList(int A[], int n)

int sum = 0, i;

for(i = 0; i < n; i++)

sum = sum + A[i];

return sum;

In above piece of code it requires

'n*2' bytes of memory to store array variable 'A[]'


2 bytes of memory for integer parameter 'n'
4 bytes of memory for local integer variables 'sum' and 'i' (2 bytes each)
2 bytes of memory for return value.

That means, totally it requires '2n+8' bytes of memory to complete its execution. Here, the
amount of memory depends on the input value of 'n'.

If the amount of space required by an algorithm is increased with the increase of input
value, then that space complexity is said to be Linear Space Complexity

4
Data Structures using C Unit - I

TIME COMPLEXITY

Every algorithm requires some amount of computer time to execute its instruction to perform the
task. This computer time required is called time complexity.

Time complexity of an algorithm can be defined as follows...

The time complexity of an algorithm is the total amount of time required by an algorithm
to complete its execution.

Generally, running time of an algorithm depends upon the following...

1. Whether it is running on Single processor machine or Multi processor machine.

2. Whether it is a 32 bit machine or 64 bit machine

3. Read and Write speed of the machine.

4. The time it takes to perform Arithmetic operations, logical operations, return value
and assignment operations etc.,

5. Input data

Calculating Time Complexity of an algorithm based on the system configuration is a very difficult
task because, the configuration changes from one system to another system. To solve this
problem, we must assume a model machine with specific configuration. So that, we can able to
calculate generalized time complexity according to that model machine.

To calculate time complexity of an algorithm, we need to define a model machine. Let us assume
a machine with following configuration...

1. Single processor machine

2. 32 bit Operating System machine

3. It performs sequential execution

4. It requires 1 unit of time for Arithmetic and Logical operations

5. It requires 1 unit of time for Assignment and Return value

6. It requires 1 unit of time for Read and Write operations

Now, we calculate the time complexity of following example code by using the above defined
model machine...
Example 1: Consider the following piece of code...

int sum(int a, int b)

return a+b;

In above sample code, it requires 1 unit of time to calculate a+b and 1 unit of time to return the
value. That means, totally it takes 2 units of time to complete its execution. And it does not

5
Data Structures using C Unit - I

change based on the input values of a and b. That means for all input values, it requires same
amount of time i.e. 2 units.

If any program requires fixed amount of time for all input values then its time complexity
is said to be Constant Time Complexity.

Example 2: Consider the following piece of code...

int sumOfList(int A[], int n)

int sum = 0, i;

for(i = 0; i < n; i++)

sum = sum + A[i];

return sum;

For the above code, time complexity can be calculated as follows...

int sumOfList(int A[], int n) Cost Repeatation Total


{
int sum = 0, i; 1 1 1
for(i=0;i<n;i++) 1 + 1 + 1 1 + (n+1) + 2n + 2
1
sum = sum + A[i]; 2 n 2n
return sum; 1 1 1
} 4n + 4
In above calculation
Cost is the amount of computer time required for a single operation in each line.
Repeatation is the amount of computer time required by each operation for all its repeatations.
Total is the amount of computer time required by each operation to execute.

Totally it takes '4n+4' units of time to complete its execution and it are Linear Time Complexity.

If the amount of time required by an algorithm is increased with the increase of input
value then that time complexity is said to be Linear Time Complexity

BIG - Oh NOTATION (O)

Big - Oh notation is used to define the upper bound of an algorithm in terms of Time Complexity.

That means Big - Oh notation always indicates the maximum time required by an algorithm for all
input values. That means Big - Oh notation describes the worst case of an algorithm time
complexity.

Big - Oh Notation can be defined as follows...

6
Data Structures using C Unit - I

Consider function f(n) the time complexity of an algorithm and g(n) is the most
significant term. If f(n) <= C g(n) for all n >= n0, C > 0 and n0 >= 1. Then we can
represent f(n) as O(g(n)).

f(n) = O(g(n))

Consider the following graph drawn for the values of f(n) and C g(n) for input (n) value on X-Axis and time
required is on Y-Axis

In above graph after a particular input value n0, always C g(n) is greater than f(n) which indicates the
algorithm's upper bound.
Example : Consider the following f(n) and g(n)...

f(n) = 3n + 2
g(n) = n

If we want to represent f(n) as O(g(n)) then it must satisfy f(n) <= C x g(n) for all values of C >
0 and n0>= 1

f(n) <= C g(n)


⇒3n + 2 <= C n

Above condition is always TRUE for all values of C = 4 and n >= 2.


By using Big - Oh notation we can represent the time complexity as follows...
3n + 2 = O(n)

7
Data Structures using C Unit - I

ARRAYS

An array is a collection of similar data type value in a single variable. It is a derived data
type in C, which is constructed from fundamental data type of C language.

Following are important terms to understand the concepts of Array.


Element Each item stored in an array is called an element.

Index Each location of an element in an array has a numerical index which is used
to identify the element.
Lower The lowest index of an array is called lower bound.
bound
Upper bound The highest index of an array is called upper bound.

Example:

int array[10]={35, 33, 42, 10, 14, 19, 27, 44, 26, 31};

For illustration, let's take C array declaration.

As per above shown illustration, following are the important points to be considered.

 Index starts with 0.


 Array length is 10 which mean it can store 10 elements.
 Each element can be accessed via its index. For example, we can fetch element at index
6 as 19.

CHARACTERISTICS OF ARRAYS

1) An array holds elements that have the same data type.

2) Array elements are stored in subsequent memory locations.

3) Two-dimensional array elements are stored row by row in subsequent memory locations.

4) Array name represents the address of the starting element.

5) Array size should be mentioned in the declaration. Array size must be a constant
expression and not a variable.

ONE-DIMENSIONAL ARRAY

A one-dimensional array is the simplest form of an array. The array is given a name and its
elements are referred by the subscripts or indices. A one-dimensional array is used to store a
large number of items in memory. Ii references the entire item in a uniform manner.

8
Data Structures using C Unit - I

Representation of Linear Arrays in Memory

The memory of the computer is simply a sequence of addressed locations.

Let LA be a linear array stored in the memory of computer

ADDRESS (LA[k]) = address of the LA[k] element of the array LA.

As the elements of the array LA are stored in consecutive memory cells, the computer does not
need to keep track of the address of every element of the array. It only needs to keep track of the
address of the first element of the array, which is denoted by:

BASE (LA)

It is called the base address of the LA. Using this base address BASE (LA), the computer
calculates the address of any element of the array by using the following formula:

ADDRESS (LA[k]) = BASE (LA) + w (k – lower bound)

Where, w – size of data type of the array LA.

The length or number of data elements of the array can be obtained from the index set by the
formula:

Length = UB – LB + 1

Example:

An automobile company uses an array AUTO to record the number of automobiles sold each
year from 1932 through 1984. Rather than beginning the index set with 1, it is more useful to
begin the index set with 1932.

AUTO[k] = number of automobiles sold in the year k

Then LB = 1932 is the lower bound and UB = 1984 is the upper bound of AUTO. By formula,
Length = UB – LB + 1 = 1984 – 1932 + 1 = 53

That is, AUTO contains 55 elements and its index set consists of all integers from 1932 through
1984.

Suppose AUTO appears in memory as:

BASE (AUTO [1932]) = 200, and w = 4 words per memory cell for AUTO. Then

9
Data Structures using C Unit - I

ADDRESS (AUTO [1932]) = 200, ADDRESS (AUTO [1933]) = 204, ADDRESS (AUTO [1934]) =
208, …

The address of the array element for the year k = 1965, can be obtained by using:
ADDRESS (LA[k]) = BASE (LA) + w (k – lower bound)

ADDRESS (AUTO [1965]) = BASE (AUTO) + 4 (1965 – lower bound)

ADDRESS (AUTO [1965]) = 200 + 4 (1965 – 1932) = 332

/* To print array values*/


#include <stdio.h>
int main()
{
int array[10]={35,33,42,10,14,19,27,44,26,31};
int i;
for(i=0;i<10;i++)
{
printf("Number %d is %d \n", i+1, array[i] ); }
return 0;
}

/* To accept 10 numbers and print them*/


#include <stdio.h>
int main()
{
int array[10];
int i;
for(i=0;i<10;i++)
{
printf("Enter the %d number \n", i+1);
scanf("%d", &array[i]);
}
for(i=0;i<10;i++)
printf("Number %d is %d \n", i+1, array[i] );

return 0;
}

/* To print array limit value and an array element address */


#include<stdio.h>
void printArray (int X[]);
main()
{
int X[15];
for(int i=0; i<15; i++)
{
X[i]=I;
}
printArray(x);
}
void printArray(int x[])
{
for(int i=0;i<15;i++)
{

10
Data Structures using C Unit - I

printf(“ Value in the array %d\n”, x[i]);


}
}
void printdetail(int x[]) {
for(int i = 0;i<15;i++)
{

printf(“Value in the array %d and address is %16lu\n”, x[i],


&x[i]);
}

TWO-DIMENSIONAL ARRAYS

 A two-dimensional array is a collection of elements placed in m rows and n columns.

 There are two subscripts in the syntax of 2D array in which one specifies the number of
rows and the other the number of columns.

 In a two-dimensional array each element is itself an array.

 The two-dimensional array is also called a matrix. Mathematically a matrix A is a


collection of elements ‗aij‘ for all i and j‘s such that 0 ≤ i<m and 0<j ≤ n. An matrix is said
to be of order m x n. A matrix can be conveniently represented by a two-dimensional
array.

 The various operations that can be performed on a matrix are: addition, multiplication.
Transposition and finding the determinant of the matrix.

An example of 2D array can be arr[2][3] containing 2 rows and 3 columns and arr[0][1] is an
element placed at 0 row and 1 column in the array. A two-dimensional array can thus be
represented as given in Figure.

Column 0 Column 1 Column 2

Row 0 arr[0][1]

Row 1

A two-dimensional array differentiates between the logical and physical view of data. A 2-D array
is a logical data structure that is useful in programming and problem solving. For example, such
an array is useful in describing an object that is physically two-dimensional such as a map or
checkerboard.
ROW MAJOR AND COLUMN MAJOR ORDER

All elements of a matrix get stored in the memory in a linear fashion. The two ways in which
elements can be represented in computer‘s memory are—Row Major Order and Column Major
Order.

In row-major representation the first row of the array occupies the first set of memory locations,
second occupies the next set, and so on.

The diagrammatic representation of two-dimensional army arr[2][3] in row major order is given in
Figure.

11
Data Structures using C Unit - I

In Figure the memory locations are first occupied by the first row of the array. Now BASE(arr)
has the address of first element of the array arr[0][0]. We also assume the size of each element
in the array with esize.

Now let us calculate the address of an element in the following 2D array:

int matrix[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 10, 11, 12} };

Formula to calculate the (j, k)th element of a 2D array of m × n dimension is:


ADDRESS(i, j) = BASE(A) + w[N(j-LB) + (k-LB)]

Where, w – word size; N – number of columns.

Let us assume that the base address of the array matrix is 100. Since w=2, LB=1, therefore,
according to the formula, address of (2, 3) th element in the array matrix will be:

ADDRESS(2, 3) = 100 + 2[4(2-1) + (3-1)]

= 100 + (4 + 2) * 2

= 100 + 12 => 112

Thus, we see that in the above matrix, address of (2, 3) th which is 7 is 112 (as depicted in the
figure.).

Similarly, the column major order representation, let us consider the same matrix:

To find the address of (j, k)th element of an array of m × n dimension, with w word size of each
element, the following formula can be used:
ADDRESS(i, j) = BASE(A) + w[M(k-LB) + (j-LB)]

12
Data Structures using C Unit - I

Where, w – word size; N – number of columns.

Let us assume that the base address of the array matrix is 100. Since w=2, LB=1, therefore,
according to the formula, address of (2, 3) th element in the array matrix will be:

ADDRESS(2, 3) = 100 + 2[3(3-1) + (2-1)]

= 100 + (6 + 1) * 2

= 100 + 14 => 114

We see that the address of the same element ((2, 3)th i.e., 7) has changed to 114 instead of 112,
in column major order representation of the array.

This is due to the fact that the element in the column major order representation are stored in a
different order, i.e., all the elements of column 1 are stored first and then all the elements of
column 2 are stored, followed by all the elements in column 3, and so on.

MULTIDIMENSIONAL ARRAYS

The array can also have more than two dimensions. For example, three-dimensional array may
be declared as: int arr[3][2][4];

An element of this is array is referenced by three subscripts. The first specifies the plane number,
the send specifies the row number and third specifies the column number. Such an array in
useful when the value is determined by three inputs.

The number of elements in any array is the product of the ranges all its dimensions. For
example, arr contains 3*2*4=24 elements. The arr[3][2][4] can he represented shown in Figure.

Therefore, the row-major representation of the elements of arr[3][2][4] is as shown in below:

It can be observed that, the last subscript varies most rapidly, and subscript is not increased until
all possible combinations of the subscript to right have been exhausted.

13
Data Structures using C Unit - I

ADVANTAGE OF ARRAY

 Code Optimization: Less code is required; one variable can store numbers of value.
 Easy to traverse data: By using array easily retrieve the data of array.
 Easy to sort data: Easily short the data using swapping technique
 Random Access: With the help of array index you can randomly access any elements
from array.

DISADVANTAGE OF ARRAY

 Fixed Size: Whatever size, we define at the time of declaration of array, we cannot
change their size, if you need more memory in that time you cannot increase memory
size, and if you need less memory in that case also wastage of memory.

DATA STRUCTURES ALGORITHMS FOR THE OPERATIONS ON ONE-DIMENSIONAL


ARRAY

Traversal Processing each element in the list.

Searching Searching or finding any element with the given value or a record with a given
key.

Insertion Adding new element to the list.

Deletion Removing an element from the list.

TRAVERSAL

Let LA be a collection of data elements stored in the computer‘s memory. To print the content of
each element of LA or count the number of elements of LA with a given property, each element
of LA will have to be accessed or processed at least once. This is called traversing.

Algorithm for traversal

Let LA be a linear array with lower bound LB and upper limit UB. The following
algorithm traverses LA applying an operation PROCESS to each element of LA.

1. Initialize counter
Set counter := LB
2. Repeat step 3 and 4 while counter <= UB
3. Visit element
Apply PROCESS to LA[counter]
4. Increase counter
Set counter := counter + 1
5. Exit

C program for traversal


#include <stdio.h>
#define N 7
int main(void)
{

14
Data Structures using C Unit - I

int k, I, LA[N]={23, 45, 56, 1, -9, -12, 123};


k=0;
while(k<=N)
{
k++;
}
for(i=0;i<N;i++)
{
printf("\n%d", LA[i]);
}
return 0;
}

SEARCHING

Searching refers to the operation of finding the location of any item in the array.

Algorithm for Search

Consider LA is a linear array with N elements and ITEM is the given item of
information. This algorithm finds the location LOC of ITEM in LA or sets
LOC=0 if search is unsuccessful.

1. [Insert ITEM at the end of the LA]


Set LA[N+1]:=ITEM
2. [ Initialize counter ]
Set LOC:=1
3. [ Search for ITEM ]
Repeat while LA[LOC]≠ITEM
Set LOC:=LOC+1
End of loop
4. [Successful?]
If LOC = N+1 then; Set LOC:=0
5. Exit

C program for Search

#include <stdio.h>
main() {
int LA[] = {1,3,5,7,8};
int item = 5, n = 5;
int i = 0, j = 0;
printf("The original array elements are :\n");

for(i = 0; i<n; i++)


{
printf("LA[%d] = %d \n", i, LA[i]);
}

while( j < n)
{
if( LA[j] == item )
{
break;
}
j = j + 1;

15
Data Structures using C Unit - I

}
printf("Found element %d at position %d\n", item, j+1);
}

INSERTION AND DELETION

 Insertion refers to the operation of adding another element to the array.


 Deletion refers to the operation of removing an element from the array.

Example:

Suppose NAME is an 8-element linear array, and suppose five names are in the array:

(a) Observe that the names are listed alphabetically, and suppose we want to keep the array
names alphabetical at all times.

(b) Suppose Ford is added to the array. Then Johnson, Smith and Wagner must each be
moved downward one Location.

(c) Next suppose Taylor is added to the array; then Wagner must be moved.

(d) Last, suppose Davis is removed from the array. Then the five names Ford, Johnson,
Smith, Taylor and Wagner must each be moved upward one Location.

Clearly such movement of data would be very expensive if thousands of names were in the
array.

Algorithm for insertion

Let LA be a linear array – the function used is INSERT (LA, N, K, ITEM). N is


the number of items. K is the positive integer such that K<=N. the following
algorithm inserts an element ITEM into Kth position of array LA.

1. Initialize counter
Set J := N
2. Repeat step 3 and 4 while J >= K
3. Move Jth element downward
Set LA[J+1] := LA[J]
4. Decrease counter
Set J := J – 1
End of step 2 loop

16
Data Structures using C Unit - I

5. Insert element
Set LA[K] := ITEM
6. Reset N
Set N := N + 1
7. Exit

C Program for Insertion

#include <stdio.h>
main()
{
int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;

printf("The original array elements are :\n");


for(i = 0; i<n; i++)
{
printf("LA[%d] = %d \n", i, LA[i]);
}
n = n + 1;
while( j >= k)
{
LA[j+1] = LA[j];
j = j - 1;
}
LA[k] = item;
printf("The array elements after insertion :\n");
for(i = 0; i<n; i++)
{
printf("LA[%d] = %d \n", i, LA[i]);
}
}

Algorithm for deletion

Let LA be a linear array – delete from the array is DELETE (LA, N, K, ITEM). N
is the number of items. K is the positive integer such that K<=N. the
following algorithm deletes Kth element from the array LA.

1. Set ITEM := LA[K]


2. Repeat for J = K to N – 1;
[Move J + 1 element upward]
Set LA[J] := LA[J+1]
End of loop
3. Reset the number N of elements in LA
Set N := N - 1
4. Exit

17
Data Structures using C Unit - I

C Program for Deletion

#include <stdio.h>
main()
{
int LA[] = {1,3,5,7,8};
int k = 3, n = 5;
int i, j;
printf("The original array elements are :\n");
for(i = 0; i<n; i++)
{
printf("LA[%d] = %d \n", i, LA[i]);
}
j = k;
while( j < n)
{
LA[j-1] = LA[j];
j = j + 1;
}
n = n -1;
printf("The array elements after deletion :\n");
for(i = 0; i<n; i++)
{
printf("LA[%d] = %d \n", i, LA[i]);
}
}

POINTERS AND ARRAYS

 When an array is declared, the compiler allocates a base address and sufficient amount
of storage to contain all the elements of the array in contiguous memory locations.

 The base address is location of the first element (index 0) of the array.

 The compiler also defines the array name as a constant pointer to the first element.

Suppose we declare an array x as follows:

int x[5] = {1, 2, 3, 4, 5};

Suppose the base address of x is 1000 and assuming that each integer requires two bytes, the
five elements will be stored as follows:

The name x is defined as a constant pointer pointing to the first element, x[0] and therefore the
value of x is 1000, the location where x[0] is stored. That is,
x = &x[0] = 1000

18
Data Structures using C Unit - I

If we declare p as an integer pointer, then we can make the pointer p to point to the array x by
the following assignment:
p = x;

This is equivalent to p = &x[0];

Now, we can access every value of x using p++ to move from one element to another. The
relationship between p and x is shown as:

p = &x[0] (= 1000)
p+1 = &x[1] (= 1002)
p+2 = &x[2] (= 1004)
p+3 = &x[3] (= 1006)
p+4 = &x[4] (= 1008)
The address of an element is calculated using its index and scale factor of the data type. For
instance,

Address of x[3] = base address + (3 × scale factor of int)

= 1000 + (3 × 2) = 1006

Note that, *(p+3) gives the value of x[3].

Write a program using pointers to compute the sum of all elements stored in an array.

main()
{
int *p, sum, i;
int x[5] = {5,9,6,3,7};
i=0;
p=x;
printf("Element Value Address");
while(i<5)
{
printf("x[%d] %d %u\n", i, *p, p);
sum = sum + *p;
i++; p++;
}
printf("\n Sum = %d\n", sum);
printf("\n &x[0] = %u\n", &x[0] );
printf("\n p = %u\n", p );
}

POINTERS AND TWO-DIMENSIONAL ARRAYS

Pointers can be used to manipulate two-dimensional arrays as well.

An element in two-dimensional array can be represented by the pointer expression as follows:

*(*(a+i)+j) or *(*(p+i)+j)

19
Data Structures using C Unit - I

p ---- pointer to first row

p+i ---- pointer to i-th row

*(p + i) ---- pointer to first element in the i-th row

*(p + i) + j ---- pointer to j-th element in the i-th row

*(*(p + i) + j) ---- value stored in the cell (i, j)

(i-th row and j-th column)

Above figure illustrates how this expression represents the element a[i][j]. The base address
of array a is &a[0][0] and starting at this address, the compiler allocates contiguous space for the
all the elements row-wise.

That is, the first element of the second row is placed immediately after the last element of the first
row, and so on.

Example:

int a[3][4] = { {15, 27, 11, 35},

{22, 19, 31, 17},

{31, 23, 14, 36}

};

20
Data Structures using C Unit - I

POINTERS AND STRINGS

Strings are treated like character arrays and therefore, they are declared and initialized as
follows:

char str[5] = ‚good‛;

The compiler automatically inserts the null character ‗\0‘ at the end of the string. C supports an
alternative method to create strings using pointer variable of type char. Example:

char *str = ‚good‛;

This create string for the literal and stores its address in the pointer variable str.

The pointer str now points to the first character of the string ―good‖ as:

We can also use the run-time assignment for given values to a string pointer. Example:

char *string1;

string1 = ‚good‛;

string1 = ‚good‛ is not a string copy, because variable string1 is a pointer, not a string.

We can print the content of the string string1 using either printf or puts function as follows:

printf(‚%s‛, string1);

puts(string1);

Write a program using pointers to determine the length of a character string


main()
{
char *name;
int length;
char *cptr = name;
name = "DELHI";
printf("%d\n", name);
while(*cptr != '\0')
{
printf("%c is stored at address %u\n", *cptr, cptr);
cptr++;
}
length=cptr - name;
printf("\n Length of the string = %d\n", length);
}

21
Data Structures using C Unit - I

ARRAY OF POINTERS

One important use of pointers is in handling of a table of strings. Consider following array of
strings:

char name[3][25];

This say that the name is a table containing three names, each with a minimum length of 25
characters. The total storage requirement for the name table are 75 bytes.

We know that rarely the individual strings will be of equal lengths.

Therefore, instead of making each row fixed number of characters, we can make it a pointer to a
string of varying length. Example:

char *name[3] = { ‚New zealand‛,

‚Australia‛,

‚India‛

};

declares name to be an array of three pointers to characters, each pointer pointing to a particular
name as:

name[0] -- New Zealand

name[1] -- Australia

name[2] -- India

this declaration allocates only 28 bytes, sufficient to hold all the characters as shown

The following statement would print out all the three names:

for(i = 0; i <= 2; i++)

printf(‚%s\n‛, name[i]);

to access the j-th character in the i-th name, we may write as:

*(name[i] + j)

22
Data Structures using C Unit - I

STRINGS
A string is a sequence of characters that is treated as single data item.

Any group of characters defined between double quotation marks is a string constant. Example:

“Well Done!”

In C printout statement is: printf(‚Well Done!‛);

Character strings are often used to build meaningful and readable programs. The common
operations performed on character strings include:

 String conversion

 String manipulation

STRING REPRESENTATIONS
 The general form of declaration of a string variable is:

o char string_name[size];

 The size determines the number of characters in the string_name. some examples are:

o char city[10];

o char name[30];

When the compiler assigns a character string to a character array, it automatically


supplies a NULL character ’\0’ at the end of the string. Therefore, the size should be
equal to the maximum number of characters in the string + 1.

 C permits a character array to be initialized in either of the following two forms:

o char city[9] = ‚NEW YORK‛;

o char city[9] = {‘N’, ‘E’, ‘W’, ‘ ‘, ‘Y’, ‘O’, ‘R’, ‘K’, ‘\0’};

The reason that city had to be 9 elements long is that the string NEW YORK containing 8
characters and one element space is provided for the NULL terminator.

 C also permits, to initialize a character array without specifying the number of elements.
For example:

o char str[] = {‘G’, ‘O’, ‘O’, ‘D’, ‘\0’};

 We can also declare the size much larger that the string size in the initializer.

o Char str[10] = ‚GOOD‛;

The storage will look like:

 Following declaration are illegal:

23
Data Structures using C Unit - I

o Char str[3] = ‚GOOD‛;

 Cannot separate the initialization from declaration:

o Char str1[10];

o str2 = ‚GOOD‛; //it is not allowed.

 Similarly,

o Char str1[10] = ‚GOOD‛;

o Char str2[10];

o str1 = str2; // error

An array name cannot be used as the left operand of an assignment operator.

STRING CONVERSION
atoi() function
 atoi() function in C language converts string data type to int data type. Syntax for atoi()
function is given below.
int atoi (const char * str);
 ―stdlib.h‖ header file supports all the type casting functions in C language.

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

int main()
{
char a[10] = "100";
int value = atoi(a);
printf("Value = %d\n", value);
return 0;
}

atof() function
 atof() function in C language converts string data type to float data type. Syntax for atof()
function is given below.
double atof (const char* string);
 ―stdlib.h‖ header file supports all the type casting functions in C language.

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

24
Data Structures using C Unit - I

int main()
{
char a[10] = "3.14";
float pi = atof(a);
printf("Value of pi = %f\n", pi);
return 0;
}

atol() function
 atol() function in C language converts string data type to long data type. Syntax for atol()
function is given below.
long int atol ( const char * str );
 ―stdlib.h‖ header file supports all the type casting functions in C language.

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

int main()
{
char a[20] = "100000000000";
long value = atol(a);
printf("Value = %ld\n", value);
return 0;
}

itoa () function
 itoa () function in C language converts int data type to string data type. Syntax for
this function is given below.
char * itoa ( int value, char * str, int base );
 ―stdlib.h‖ header file supports all the type casting functions in C language. But, it is a non
standard function.

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

int main()
{
int a=54325;

25
Data Structures using C Unit - I

char buffer[20];
itoa(a,buffer,2); // here 2 means binary
printf("Binary value = %s\n", buffer);

itoa(a,buffer,10); // here 10 means decimal


printf("Decimal value = %s\n", buffer);

itoa(a,buffer,16); // here 16 means Hexadecimal


printf("Hexadecimal value = %s\n", buffer);
return 0;
}

ltoa() function
 ltoa() function in C language converts long data type to string data type. Syntax for ltoa()
function is given below.
char *ltoa(long N, char *str, int base);
 ―stdlib.h‖ header file supports all the type casting functions in C language.

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

int main()
{
long a=10000000;
char buffer[50];
ltoa(a,buffer,2); // here 2 means binary
printf("Binary value = %s\n", buffer);

ltoa(a,buffer,10); // here 10 means decimal


printf("Decimal value = %s\n", buffer);

ltoa(a,buffer,16); // here 16 means Hexadecimal


printf("Hexadecimal value = %s\n", buffer);
return 0;
}

26
Data Structures using C Unit - I

STRING MANIPULATION
 String.h header file supports all the string functions in C language.

strcat() function
 strcat( ) function in C language concatenates two given strings. It concatenates source
string at the end of destination string. Syntax for strcat( ) function is given below.

char * strcat ( char * destination, const char * source );

 Example:
strcat ( str2, str1 ); – str1 is concatenated at the end of str2.
strcat ( str1, str2 ); – str2 is concatenated at the end of str1.

#include <stdio.h>

#include <string.h>

int main( )

char source[ ] = " fresh2refresh" ;

char target[ ]= " C tutorial" ;

printf ( "\nSource string = %s", source ) ;

printf ( "\nTarget string = %s", target ) ;

strcat ( target, source ) ;

printf ( "\nTarget string after strcat( ) = %s", target ) ;

strcpy() function

 strcpy( ) function copies contents of one string into another string. Syntax for strcpy
function is given below.

char * strcpy ( char * destination, const char * source );

 Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.

#include <stdio.h>

#include <string.h>

int main( )

char source[ ] = "fresh2refresh" ;

27
Data Structures using C Unit - I

char target[20]= "" ;

printf ( "\nsource string = %s", source ) ;

printf ( "\ntarget string = %s", target ) ;

strcpy ( target, source ) ;

printf ( "\ntarget string after strcpy( ) = %s", target ) ;

return 0;

strlen() function

 strlen( ) function in C gives the length of the given string. Syntax for strlen( ) function is
given below.

size_t strlen ( const char * str );

 strlen( ) function counts the number of characters in a given string and returns the
integer value.

 It stops counting the character when null character is found. Because, null character
indicates the end of the string in C.

#include <stdio.h>

#include <string.h>

int main( )

int len;

char array[20]="fresh2refresh.com" ;

len = strlen(array) ;

printf ( "\string length = %d \n" , len ) ;

return 0;

strcmp() function

 strcmp( ) function in C compares two given strings and returns zero if they are same.

 If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns >
0 value. Syntax for strcmp( ) function is given below.

int strcmp ( const char * str1, const char * str2 );

 strcmp( ) function is case sensitive. i.e, ―A‖ and ―a‖ are treated as different characters.

28
Data Structures using C Unit - I

#include <stdio.h>

#include <string.h>

int main( )

char str1[ ] = "fresh" ;

char str2[ ] = "refresh" ;

int i, j, k ;

i = strcmp ( str1, "fresh" ) ;

j = strcmp ( str1, str2 ) ;

k = strcmp ( str1, "f" ) ;

printf ( "\n%d %d %d", i, j, k ) ;

return 0;

strlwr() function

 strlwr( ) function converts a given string into lowercase. Syntax for strlwr( ) function is
given below.

char *strlwr(char *string);

 strlwr( ) function is non standard function which may not available in standard library in
C.

#include<stdio.h>

#include<string.h>

int main()

char str[ ] = "MODIFY This String To LOwer";

printf("%s\n",strlwr (str));

return 0;

strupr() function

 strupr( ) function converts a given string into uppercase. Syntax for strupr( ) function is
given below.

char *strupr(char *string);

29
Data Structures using C Unit - I

 strupr( ) function is non standard function which may not available in standard library in
C.

#include<stdio.h>

#include<string.h>

int main()

char str[ ] = "Modify This String To Upper";

printf("%s\n",strupr(str));

return 0;

strrev() function

 strrev( ) function reverses a given string in C language. Syntax for strrev( ) function is
given below.

char *strrev(char *string);

 strrev( ) function is non standard function which may not available in standard library in
C.

#include<stdio.h>

#include<string.h>

int main()

char name[30] = "Hello";

printf("String before strrev( ) : %s\n",name);

printf("String after strrev( ) : %s",strrev(name));

return 0;

30

You might also like