Você está na página 1de 26

Data Structures Using C

Dedicated to all my well wishers

Bhavesh Kumar, MCA, ME(CSE)


Certified Trainer & Group Leader
NIIT Ltd., ILS Division, Bangalore
E-Mail : itsbhaveshkumar@gmail.com
bhavesh.kumar@niit.com

Data Structures [UNIT-I] Bhavesh Kumar Page 1


Data Structures
----------------------------------------------------------------------------------------------------------------------------- -------
Data
------------------------------------------------------------------------------------------------------------------------------------
These are raw facts and figures.
These are simply values or set of values.
Data is represented in the form of text, number, figures, tables, graphs, pictures etc.
For e.g. Amit, 18, BCA etc.

----------------------------------------------------------------------------------------------------------------------------- -------
Information
------------------------------------------------------------------------------------------------------------------------------------
It is processed data.
For e.g. Information about business transactions, information about students performance etc.

------------------------------------------------------------------------------------------------------------------------------------
Data Structure
----------------------------------------------------------------------------------------------------------------------------- -------
It is a method of storing data in a computer so that it can be used efficiently.
It is defined as an organized collection of data, their relationship and allowed operations.
It is defined as a logical or mathematical model of a particular organization of data.
The data structure deals with the followings
How the data is organized in the memory.
How efficiently the data can be stored in the memory.
How efficiently the data can be retrieved, processed and manipulated.
The kind of operations to be performed on data.
The ways to represent possible logical relations between different data.
Examples of data structures Array, Stack, Linked List, Queue, Tree, Graph etc.
Basically the study of data structure includes the following three steps
ALGORITHM - Logical or mathematical description of the structure.
OPERATIONS Implementation of the structure on a computer.
TIME-SPACE COMPLEXITY Quantitative analysis of the structure, which includes the
amount of memory needed to store the structure and the time required to process the
structure.
Followings are the six major operations associated with any data structure
1. TRAVERSING Accessing each record exactly once so that certain items in
the record may be processed.
2. SEARCHING Finding the location of the record with a given key value, or
finding the location of all records which satisfy one or more conditions.
3. INSERTING Adding a new record to the data structure.
4. DELETING Removing a record from the data structure.
5. SORTING Arranging records in the data structure in a particular order.
6. MERGING Joining two similar types of data structures.

Data Structures [UNIT-I] Bhavesh Kumar Page 2


----------------------------------------------------------------------------------------------------------------------------- -------
Classification of Data Structure
------------------------------------------------------------------------------------------------------------------------------------
Primitive Data Structures - These are directly operated upon by machine level instructions. The
memory representations of these data structures vary from one machine to another machine.
Followings are Primitive Data Structures -
Integer
Floating Point
Character
Double
Boolean
Pointers
Non-Primitive Data Structures These Data Structures can not be operated upon directly by the
machine level instructions. Non-Primitive data structures are of two types -
Linear Data Structures - A Data structure is called as linear if its elements form a sequence or a
linear list. These data structure establishes the relationship of adjacency between the elements.
Followings are linear data structures -
Arrays It is a finite set of homogeneous elements stored in adjacent memory locations. It is
represented by a single name. Each location element is identified by a single name
with its index. The index value starts with 0. The first element is a[0], second is a[1]
and so on.

A[0] A[1] A[2] A[3] A[4]

Stacks It is a data structure in which data is inserted and deleted at one end called the TOP of
stack. It operates on Last-In-First-Out (LIFO) or First-In-Last-Out (FILO) order.

Insertion or PUSH Deletion or POP

St[5]

St[4]
9 TOP of Stack
St[3]
8
St[2]
4
St[1]
9
St[0]

Data Structures [UNIT-I] Bhavesh Kumar Page 3


Queues It is a data structure in which data is inserted from one end called the REAR and data
items can be deleted from the other end called the FRONT. It operates on First-In-First-Out
(FIFO) order.

FRONT, Deletion REAR, Insertion


A[0] A[1] A[2] A[3] A[4]

Linked Lists It is a linear collection of data items called nodes. Each node contains two
fields
i) Information or data field
ii) Link field
Each node contains the data and a pointer pointing to the next node of the list. The first node is
pointed by HEAD pointer. The first node points to the second node, second node points to the
third node and so on.
HEAD Pointer
Add. Of
NODE1

Data Add. Of NODE2 Data Add. Of NODE3 Data NULL

Non-Linear Data Structures A data structure in which data items are not arranged in order are
called as Non-linear Data Structures. They establish relationship other than the adjacency
relationship. Followings are non-linear data structures -
Trees This data structure is used to represent hierarchical relationship between elements.
Tree contains data in nodes which are linked to each other using links or pointers. The primary
node is called as the ROOT node, from which all other branch nodes in the tree comes out.
These branch nodes are called as sub-trees.

ROOT Node

Left Subtree Right Subtree


Child Node

Data Structures [UNIT-I] Bhavesh Kumar Page 4


Graphs It consists a set of elements called nodes and a set of edges such that each edge is
identified with a unique unordered pair of nodes.

Other ways of categorizing Data Structures are


Homogeneous Data Structures Array
Non-Homogeneous or Heterogeneous Data Structures Structure, Union, Class

Static Data Structures Size is fixed, uses Static Memory Allocation.


Dynamic Data Structures Size is not fixed, uses Dynamic Memory Allocation

Data Structures [UNIT-I] Bhavesh Kumar Page 5


----------------------------------------------------------------------------------------------------------------------------- -------
Algorithms Complexity
----------------------------------------------------------------------------------------------------------------------------- -------
Data structures are implemented using algorithms.

An algorithm is a procedure that you can write as a C function or program, or any other language.

An algorithm states explicitly how the data will be manipulated.

There can be various solutions to a problem and hence, there will be different algorithms to solve the
same problem.

Some algorithms are more efficient than others. We would prefer to choose an efficient algorithm.

To find the efficiency of any algorithm we must analyze the algorithms.

We analyze algorithms to know the followings-


To predict the resources that the algorithm requires, like
1. Computational Time (CPU Consumption)
2. Memory Space (RAM Consumption)
3. Communication Bandwidth Consumption
To predict the running time of an algorithm in terms of total number of primitive
operations executed.

The complexity of an algorithm is a function describing the efficiency of the algorithm in terms of the
amount of data the algorithm must process.

We can measure Algorithmic Complexity in terms of


Memory
Time
Number of Steps
Number of Particular Operations
1. Number of Disk Operations
2. Number of Network Packets

There are two main complexity measures for the efficiency of an algorithm:
Time complexity
It is a function describing the amount of time an algorithm takes in terms of the amount of
input to the algorithm, processing, etc.
"Time" can mean the number of memory accesses performed, the number of comparisons
between integers, the number of times some inner loop is executed, or some other natural
unit related to the amount of real time the algorithm will take.

Space complexity
It is a function describing the amount of memory (space) an algorithm takes in terms of the
amount of input to the algorithm, processing, etc.
We often speak of "extra" memory needed, not counting the memory needed to store the
input itself.

Data Structures [UNIT-I] Bhavesh Kumar Page 6


Space complexity is sometimes ignored because the space used is minimal and/or obvious,
but sometimes it becomes an important issue as time.

The Complexity of algorithms can be represented at three different levels


Worst-Case An upper bound on the running time/memory space requirements for any input of
given size.
Average-Case An average bound on the running time/memory space requirements.
Best-Case The lower bound on the running time/memory space requirements.

Data Structures [UNIT-I] Bhavesh Kumar Page 7


----------------------------------------------------------------------------------------------------------------------------- -------
Mathematical Notations and Functions
------------------------------------------------------------------------------------------------------------------------------------
Floor and Ceiling Functions: If x is a real number, then it means that x lies between two integers which
are called the floor and ceiling of x.

In mathematics and computer science, the floor and ceiling functions map a real number to the largest
previous or the smallest following integer, respectively.

|_x_| is called the floor of x. It is the greatest integer that is not greater than x.
| x | is called the ceiling of x. It is the smallest integer that is not less than x.

If x is itself an integer, then |_x_| = | x |, otherwise |_x_| + 1 = | x | E.g.


|_3.14_| = 3
|_-8.5_| = -9
|_7_| = 7
| 3.14 |= 4
| -8.5 | = -8
| 7 |= 7

X Floor Ceil
-1.1 -2 -1
0 0 0
1.01 1 2
2.9 2 3
3 3 3

Remainder Function (Modular Arithmetic): If k is any integer and M is a positive integer, then:
k(mod M) gives the integer remainder when k is divided by M. For e.g.
25(mod 7) = 4
25(mod 5) = 0

Integer Functions: If x is a real number, then integer function INT(x) will convert x into integer and the
fractional part is removed. For e.g.
INT(3.14) = 3
INT(-8.5) = -8

Absolute Value Function: The absolute function ABS(x) or | x | gives the absolute value of x i.e. it gives
the positive value of x even if x is negative. For e.g.
ABS(-15) = 15 or ABS | -15| = 15
ABS(7) = 7 or ABS | 7 | = 7
ABS(-3.33) = 3.33 or ABS | -3.33 | = 3.33

Data Structures [UNIT-I] Bhavesh Kumar Page 8


Factorial Function: n! denotes the product of the positive integers from 1 to n. n! is read as n factorial,
i.e. n! = 1 * 2 * 3 * .. * (n-2) * (n-1) * n
For e.g.
4! = 1 * 2 * 3 * 4 = 24
5! = 5 * 4! = 120

Permutations: Let we have a set of n elements. A permutation of this set means the arrangement of the
elements of the set in some order. For e.g. - Suppose the set contains a, b and c. The various permutations
of these elements can be: abc, acb, bac, bca, cab, cba.

If there are n elements in the set then there will be n! permutations of those elements. It means if the set
has 3 elements then there will be 3! = 1 * 2 * 3 = 6 permutations of the elements.
Exponent: Exponent means how many times a number is multiplied by itself. If m is a positive integer,
then:
am = a * a * a * .. * a (m times)
and
-m m
a =1/a
For e.g.
24 = 2 * 2 * 2 * 2 = 16
2-4 = 1 / 24 = 1 / 16

Logarithms: The concept of logarithms is related to exponents. If b is a positive number, then the
logarithm of any positive number x to the base b is written as logbx. It represents the exponent to which b
should be raised to get x i.e. y = logbx and by = x
E.g.
log28 = 3, since 23=8
log100.001 = - 3, since 10-3 = 0.001
logb1 = 0, since b0 = 1
logbb = 1, since b1 = b

Summation Symbol (Sums): The symbol which is used to denote summation is a Greek letter Sigma .
Let a1, a2, a3, .. , an be a sequence of numbers. Then the sum a1 + a2 + a3 + .. + an will be written
as:
n
aj
j=1
where j is called the dummy index or dummy variable. E.g.
n
j = 1 + 2 + 3 +..+ n
j=1

Data Structures [UNIT-I] Bhavesh Kumar Page 9


----------------------------------------------------------------------------------------------------------------------------- -------
Asymptotic Notations
------------------------------------------------------------------------------------------------------------------------------------
A problem may have numerous algorithmic solutions.

In order to choose the best algorithm for a particular task, you need to be able to judge how long a
particular solution will take to run. Or, more accurately, you need to be able to judge how long two
solutions will take to run, and choose the better of the two.

You don't need to know how many minutes and seconds they will take, but you do need some way to
compare algorithms against one another.

Now let us consider how we would go about comparing the complexity of two algorithms-
Let f(n) be the cost, in the worst case, of one algorithm, expressed as a function of the input
size n, and
g(n) be the cost function for the other algorithm.
E.g., for sorting algorithms,
f(10) and g(10) would be the maximum number of steps that the algorithms would take on a
list of 10 items. If, for all values of n >= 0, f(n) is less than or equal to g(n), then the algorithm
with complexity function f is strictly faster.

The Big-O Notation (For Best Case, Upper Bound)


The O (pronounced big-oh) is the formal method of expressing the upper bound of an algorithm's
running time. It's a measure of the longest amount of time it could possibly take for the algorithm to
complete.

More formally, for non-negative functions, f(n) and g(n), if there exists an integer and a constant
c > 0 such that for all integers , f(n) cg(n), then f(n) is Big O of g(n). This is denoted as
"f(n) = O(g(n))".

So, let's take an example of Big-O. Say that f(n) = 2n + 8, and g(n) = . Can we find a constant ,
so that 2n + 8 <= ? The number 4 works here, giving us 16 <= 16. For any number n greater than 4,
this will still work. Since we're trying to generalize this for large values of n, and small values (1, 2, 3)
aren't that important, we can say that f(n) is generally faster than g(n); that is, f(n) is bound by g(n),
and will always be less than it.

The Big-Omega Notation (For Worst Case, Lower Bound)


For non-negative functions, f(n) and g(n), if there exists an integer and a constant c > 0 such that
for all integers , f(n) cg(n), then f(n) is omega of g(n). This is denoted as "f(n) = (g(n))".

This is almost the same definition as Big Oh, except that "f(n) cg(n)", this makes g(n) a lower bound
function, instead of an upper bound function.

Data Structures [UNIT-I] Bhavesh Kumar Page 10


The Theta Notation (For Average Case)
For non-negative functions, f(n) and g(n), f(n) is theta of g(n) if and only if f(n) = O(g(n)) and
f(n) = (g(n)). This is denoted as "f(n) = (g(n))".

In this, it is said that the function, f(n) is bounded both from the top and bottom by the same function,
g(n).

The theta notation is denoted by Q.

Little-O Notation
For non-negative functions, f(n) and g(n), f(n) is little o of g(n) if and only if f(n) = O(g(n)), but
f(n) (g(n)). This is denoted as "f(n) = o(g(n))".

This represents a loose bounding version of Big O. g(n) bounds from the top, but it does not bound the
bottom.

Little Omega Notation


For non-negative functions, f(n) and g(n), f(n) is little omega of g(n) if and only if f(n) = (g(n)), but
f(n) (g(n)). This is denoted as "f(n) = (g(n))".

Much like Little Oh, this is the equivalent for Big Omega. g(n) is a loose lower boundary of the
function f(n); it bounds from the bottom, but not from the top.

Data Structures [UNIT-I] Bhavesh Kumar Page 11


----------------------------------------------------------------------------------------------------------------------------- -------
Algorithmic Notations
----------------------------------------------------------------------------------------------------------------------------- -------
An algorithm is a finite step-by-step procedure that takes some raw data as input and transforms it to a
required result.

An algorithm is a tool for solving a well-specified computational problem.

An algorithm is composed of finite set of steps, each may require one or more operations.

In fact, a data structure and an algorithm should be thought of as a unit, neither one making sense
without the other.

An algorithm can be described in many ways. A natural language such as English can be used to write
an algorithm but generally algorithms are written in English-like pseudocode that resembles with high
level programming languages

An algorithm does not follow exactly any programming language, so that it does not require any
translator. Therefore, we cant run algorithm with the help of compiler/interpreter, just we can dry run
to check the results.

Every algorithm must satisfy the following criteria:


Input: In every algorithm, there must be zero or more data that are externally supplied.
Output: At least one data is produced as result or information.
Definiteness: Each instruction must be clear and unambiguous (i.e., clearly one meaning).
Finiteness: If we trace out the instructions of an algorithm, then for all cases, the algorithm will
terminate after a finite number of steps.
Effectiveness: Every instruction must be feasible and provides some basis towards the solution.

Following are few of the conventions being used to write an algorithm


1. Name of algorithm: Every algorithm is given an identifying name conventionally written in
capital letters.

2. Introductory comment: The algorithm name is followed by a brief description of the tasks
the algorithm performs and any assumptions that have been made. The description can give
the name and types of the variables used in the algorithm. Comments specify no action and
are included only for clarity.

3. Steps: Each algorithm is made of a sequence of numbered steps and each step can have an
ordered sequence of statements, which describe the tasks to be performed. The statements in
each step are executed in a left-to-right order.

4. Data type: Data types are assumed simple such as integer, real, char, boolean and other data
structures such as array, pointer, structure are used. Array ith element can be described as
A[i] and (i, j) element can be described as A[i, j].

5. Assignment statement: The assignment statement is indicated by placing equal (=) or :=


between the variable (in left hand side) and expression or value(s) (in right hand side). For
example, addition of a and b is assigned in variable a.
a=a+b or a := a + b
Data Structures [UNIT-I] Bhavesh Kumar Page 12
6. Expression: There are three expressions: arithmetic, relational and logical. The arithmetic
expression used arithmetic operator such as /, *, +, , relational expression used relational
operator such as <, <=, >, >=. <>, = and logical expression used logical operator such as not,
or, and. There are two boolean values, true or false.

7. If statement: If statement can have one of the following forms:


(a) if condition then
statement(s)

(b) if condition then


statement(s)
else
statement(s)

(c) if condition then


statement(s)
else if condition then
statement(s)
else if condition then
statement(s)
----------------------------
else
statement(s)

8. Case statement: Case statement has the form:


Select case (expression)
case value 1: statement (s)
case value 2: statement (s)
.
.
.
case value n: statement (s)
default: statement (s)

9. Looping statements: Various looping statements can be represented as -


(a) while (condition) do
{
statement(s)
}

(b) for variable = start_value to final_value step increment_value do


{
statement(s)
}

(c) repeat
{
statement(s)
} until (condition)
Data Structures [UNIT-I] Bhavesh Kumar Page 13
10. Input and output: For input of data we use
read(variable name)
and for output of data we use
write(variable name) or write(expression)
If more than one input or output data are there, then we can use comma as separator among
the variable names.

11. Goto statement: The goto statement causes unconditional transfer of control to the step
referenced. Thus statement goto step N will cause transfer of control to step N.

12. End statement: The end statement is used to terminate an algorithm. It is usually the last step
and optionally algorithm name is written after the end.

13. Return Statement: A return statement can be represented as


return expression

14. Functions or Procedures: A function is used to return single value to the calling function.
Transfer of control and returning of the value are accomplished by return(value) statement. A
function begins as follows:
function function_name (parameters list)

Data Structures [UNIT-I] Bhavesh Kumar Page 14


String
----------------------------------------------------------------------------------------------------------------------------- -------
Definition
------------------------------------------------------------------------------------------------------------------------------------
Strings in C are represented by arrays of characters. A string in C is a sequence of zero or more
characters followed by a NULL character. The null or string-terminating character is represented by a
character escape sequence, \0.

If we want to have an array of characters without the null character as the last element, then we need to
have an ordinary character array, rather than a string constant.

String constants have double quote marks around them, and can be assigned to char pointers as shown
below. Alternatively, you can assign a string constant to a char array - either with no size specified, or
you can specify a size, but don't forget to leave a space for the null character!
char *string_1 = "Hello";
char string_2[] = "Hello";
char string_3[6] = "Hello";

In fact, C's only truly built-in string-handling is that it allows us to use string constants (also
called string literals) in our code. Whenever we write a string, enclosed in double quotes, C
automatically creates an array of characters for us, containing that string, terminated by
the \0 character. For example, we can declare and define an array of characters, and initialize it with a
string constant:
char string[] = "Hello, world!";
In this case, we can leave out the dimension of the array, since the compiler can compute it for us
based on the size of the initializer (14, including the terminating \0). This is the only case where the
compiler sizes a string array for us, however; in other cases, it will be necessary that we decide how
big the arrays and other data structures we use to hold strings are.

----------------------------------------------------------------------------------------------------------------------------- -------
Storing Strings
------------------------------------------------------------------------------------------------------------------------------------
Strings can be stored in three ways
1. Fixed Length Storage It is to define strings with some fixed size, so that the number of characters in
each string will be fixed. Size of the string is being specified at the time of string creation. For e.g.
char str[20];
Advantage i) implementation is easy, ii) updation is easy.
Disadvantage Wastage of memory if string length is less than fixed length.

2. Variable Length Storage with Fixed Maximum It is to define strings with some fixed size, so that the
number of characters in each string will be fixed. Size of the string is being specified at the time of string
creation. However, a \0 character can be added to mark the end of string, or the string length as an
additional item can be listed.
Advantage Saves memory space and well suited for strings which are permanent.
Disadvantage Inefficient when the string is frequently changing.

Data Structures [UNIT-I] Bhavesh Kumar Page 15


3. Variable Length Storage without Fixed Maximum or Linked Storage It is to define strings without
any fixed size with the help of character pointer.
char *str;
Advantage Storage is efficient even if the string is frequently changing. Updation, Insertion deletion
operations are easier.
Disadvantage Complex to use.

----------------------------------------------------------------------------------------------------------------------------- -------
String Handling Functions
------------------------------------------------------------------------------------------------------------------------------------
With every C compiler a large set of useful string handling library functions are provided. Following is
the list of more commonly used functions along with their purpose. To use any of these functions we
need to include <string.h> in our program.

All the string handling functions are prototyped in: string.h or stdio.h standard header file. So while
using any string related function, don't forget to include either stdio.h or string.h. May be your
compiler differes so please check before going ahead.

Function Use

strlen Finds length of a string


strlwr Converts a string to lowercase
strupr Converts a string to uppercase
Strcat Appends one string at the end of another
strncat Appends first n characters of a string at the end of another
strcpy Copies a string into another
strncpy Copies first n characters of one string into another
strcmp Compares two strings
strncmp Compares first n characters of two strings
strcmpi Compares two strings without regard to case ("i" denotes that
this function ignores case)
stricmp Compares two strings without regard to case (identical to strcmpi)
strnicmp Compares first n characters of two strings without regard to case
strdup Duplicates a string
strchr Finds first occurrence of a given character in a string
strrchr Finds last occurrence of a given character in a string
Strstr Finds first occurrence of a given string in another string
Strset Sets all characters of string to a given character
strnset Sets first n characters of a string to a given character
Strrev Reverses string

Out of the above list functions strlen( ), strcpy( ), strcat( ) and strcmp( ), are the most commonly
used functions.

Data Structures [UNIT-I] Bhavesh Kumar Page 16


strlen( ) - This function counts the number of characters present in a string. While calculating the
length it doesnt count \0. Its usage is illustrated in the following program.
#include<string.h>
#include<stdio.h>
#include<conio.h>
void main()
{
char str[100];
clrscr();
printf("Enter the string : ");
gets(str);
printf(Length of the given string is %d,strlen(str));

getch();
}

Strlwr() This function converts the string passed to it into lowercase letters. Its example is as

#include<string.h>
#include<stdio.h>
#include<conio.h>
void main()
{
char str[100];
clrscr();
printf("Enter the string : ");
gets(str);
puts(strlwr(str));

getch();
}

Strupr() This function converts the string passed to it into uppercase letters. Its example is as
#include<string.h>
#include<stdio.h>
#include<conio.h>
void main()
{
char str[100];
clrscr();
printf("Enter the string : ");
gets(str);
puts(strupr(str));

getch();
}

Data Structures [UNIT-I] Bhavesh Kumar Page 17


Strcat() - This function concatenates the source string at the end of the target string. For example,
IFIM and College on concatenation would result into a string IFIMCollege. Here is an example
of strcat( ).
#include<string.h>
#include<stdio.h>
#include<conio.h>
void main( )
{
char source[ ] = "College";
char target[30] = "IFIM";
strcat ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
}
And here is the output...
source string = College
target string = IFIMCollege

Strncat() - This function concatenates the n characters of source string at the end of the target string.
For example,
#include<string.h>
#include<stdio.h>
#include<conio.h>

void main( )
{
char source[ ] = "Folks!";
char target[30] = "Hello";
strncat ( target, source,3);
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
}
And here is the output...
source string = Folks!
target string = HelloFol

strcpy( ) - This function copies the contents of one string into another. The base addresses of the
source and target strings should be supplied to this function. Here is an example of strcpy( ) in
action...
#include<string.h>
#include<stdio.h>
#include<conio.h>
void main( )
{

Data Structures [UNIT-I] Bhavesh Kumar Page 18


char source[ ] = "Indian" ;
char target[20] ;
strcpy ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
}
And here is the output...
source string = Indian
target string = Indian

On supplying the base addresses, strcpy( ) goes on copying the characters in source string into the
target string till it doesn't encounter the end of source string (\0). It is our responsibility to see to it
that the target strings dimension is big enough to hold the string being copied into it. Thus, a string
gets copied into another, character by character.

strcmp( ) - This is a function which compares two strings to find out whether they are same or
different. The two strings are compared character by character until there is a mismatch or end of one
of the strings is reached, whichever occurs first. If the two strings are identical, strcmp( ) returns a
value zero. If theyre not, it returns the numeric difference between the ASCII values of the first non-
matching pairs of characters. Here is a program which puts strcmp( ) in action.
#include<string.h>
#include<stdio.h>
#include<conio.h>
void main( )
{
char string1[ ] = "Jerry" ;
char string2[ ] = "Ferry" ;
int i, j, k ;
i = strcmp ( string1, "Jerry" ) ;
j = strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry boy" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
}

And here is the output...


0 4 -32 or 0 1 -1
strncmp( ) - This is a function which compares two strings with their first n characters to find out
whether they are same or different.
#include<string.h>
#include<stdio.h>
#include<conio.h>
void main( )
{
char string1[ ] = "Jerry" ;
char string2[ ] = "Ferry" ;

Data Structures [UNIT-I] Bhavesh Kumar Page 19


int i, j, k ;
i = strncmp ( string1, "Jersy",3 ) ;
j = strncmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry boy" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
}
And here is the output...
040 or 010

strcmpi( ) or stricmp( ) - This is a function which compares two strings to find out whether they are
same or different and ignores the cases.
#include<string.h>
#include<stdio.h>
#include<conio.h>
void main( )
{
char string1[ ] = "Jerry" ;
int i;
i = strcmpi( string1, "JERRY" ) ;
printf ( "\n%d ", i) ;
}
And here is the output...
0
strchr( ) This function finds the first occurrence of a given character in a string.
#include<string.h>
#include<stdio.h>
#include<conio.h>
void main( )
{
char string1[ ] = "Jerry" ;
char *ptr;
ptr = strchr(string1,r);
printf ( "\n%d ", ptr-string1) ;
}
And here is the output...
2
strstr( ) - This function finds the first occurance of a given string or substring in a string.
#include<string.h>
#include<stdio.h>
#include<conio.h>
void main( )
{
char string1[ ] = "Jerry" ;
char *ptr;

Data Structures [UNIT-I] Bhavesh Kumar Page 20


ptr = strstr(string1,rr);
printf ( "\n%d ", ptr-string1) ;
}
And here is the output...
2

strrev( ) - This function reverses the string.


#include<string.h>
#include<stdio.h>
void main( )
{
char string1[ ] = "Jerry" ;
printf ( "\n%s ", strrev(string1)) ;
}
And here is the output...
yrreJ

Data Structures [UNIT-I] Bhavesh Kumar Page 21


----------------------------------------------------------------------------------------------------------------------------- -------
Write a menu driven C program to perform the following string operations without using string functions:
(i) String Length (ii) String Concatenation (ii) String Reverse
----------------------------------------------------------------------------------------------------------------------------- -------
ALGORITHM

String Length Algorithm


String_length(string)
Where, string represents the string whose length has to be calculated.
STEP 1 Set I = 0
STEP 2 Repeat through STEP 3 until (string[I] = \0)
STEP 3 I = I + 1
STEP 4 PRINT Length of the string is,I
STEP 5 Exit.

String Concatenation Algorithm


String_concat(string1,string2)
Where, string1 represents the target string, and
string2 represents the source string.
STEP 1 Set L = String_length(string1)
STEP 2 Set I = L and J = 0
STEP 3 Repeat through STEP 4 until (string2[J] = \0)
STEP 4 a) string1[I] = string2[J]
b) I = I + 1 and J = J + 1
STEP 5 Set string1[I] = \0
STEP 6 PRINT Concatenated string is,string1
STEP 7 Exit.

String Reverse Algorithm


String_reverse(string)
Where, string represents the string to be reversed.
STEP 1 Define rev_str
STEP 2 Set L = String_length(string)
STEP 3 Set I = L-1 and J = 0
STEP 4 Repeat through STEP 5 until (I >= 0)
STEP 5 a) rev_str[J] = string[I]
b) I = I - 1 and J = J + 1
STEP 5 Set rev_str[J] = \0
STEP 6 PRINT Reversed string is,rev_str
STEP 7 Exit.

Data Structures [UNIT-I] Bhavesh Kumar Page 22


PROGRAM -
#include<stdio.h>
#include<conio.h>

int findStringLength(char*);
void concatenateStrings(char*,char*);
char* reverseString(char*);

void main()
{
char str1[100],str2[100],choice;
int ch;

clrscr();

do
{ clrscr();
printf("1. To Find String Length\n");
printf("2. To Concatenate Two Strings\n");
printf("3. To Reverse a String\n");
printf("4. Exit\n");

printf("Enter your choice [1-4] : ");


scanf("%d",&ch);

switch (ch)
{
case 1:
printf("Enter the String : ");
fflush(stdin);
gets(str1);
printf("Length of %s is %d.",str1,findStringLength(str1));
break;
case 2:
printf("Enter the first String : ");
fflush(stdin);
gets(str1);

printf("Enter the second String : ");


fflush(stdin);
gets(str2);

printf("First String is : %s\n",str1);


printf("Second String is : %s\n",str2);

concatenateStrings(str1,str2);

printf("First String after concatenation : %s",str1);

Data Structures [UNIT-I] Bhavesh Kumar Page 23


printf("\nSecond String after concatenation : %s",str2);
break;
case 3:
printf("Enter the String : ");
fflush(stdin);
gets(str1);

printf("Reverse of %s is %s.",str1,reverseString(str1));
break;
case 4:
exit(0);
default:
printf("Invalid Choice\n");
}

printf("\nDo you want to continue [y/Y/n/N]: ");


fflush(stdin);
scanf("%c",&choice);
}while(choice=='y' || choice=='Y');
}

int findStringLength(char *p)


{
int i=0;

while(*p!='\0')
{
i++;
p++;
}
/*
for(i=0;*p!='\0';i++,p++);
*/
return i;
}

void concatenateStrings(char *s1,char *s2)


{
int i,j;
int l1 = findStringLength(s1);

for(i=l1,j=0;*(s2+j)!='\0';i++,j++)
{
*(s1+i) = *(s2+j);
}
*(s1+i)='\0';

Data Structures [UNIT-I] Bhavesh Kumar Page 24


char* reverseString(char *s1)
{
char revs[100];
int l1 = findStringLength(s1);

int i,j;

for(i=l1-1,j=0;i>=0;i--,j++)
{
revs[j] = *(s1+i);
}
revs[j] = '\0';

return revs;
}

Data Structures [UNIT-I] Bhavesh Kumar Page 25


----------------------------------------------------------------------------------------------------------------------------- -------
Pattern matching
------------------------------------------------------------------------------------------------------------------------------------

Sdvvdvv

----------------------------------------------------------------------------------------------------------------------------- -------
Word/Text Processing
----------------------------------------------------------------------------------------------------------------------------- -------

sdvvdvv

------------------------------------------------------------------------------------------------------------------------------------
Abstract Data Type
----------------------------------------------------------------------------------------------------------------------------- -------

sdvvdvv

Data Structures [UNIT-I] Bhavesh Kumar Page 26

Você também pode gostar