You are on page 1of 46

Data Structure and

Algorithms
Teacher - Daw Theingi AyeWai Yan Thein

1 | Page
Structure.

Data

Task 1 (LO1: AC1.1, 1.2, 1.3 & M2)


1.1 produce design specification for data structures explain the
valid operations that can be carried out on the structures
Data Structure
A data structure is a specialized format for organizing and storing data.
General data structure types include the array, the file, the record, the
table, the tree, and so on. Any data structure is designed to organize
data to suit a specific purpose so that it can be accessed and worked
with in appropriate ways. In computer programming, a data structure
may be selected or designed to store data for the purpose of working on
it with various algorithms.
Interrelationship among data elements that determine how data is
recorded, manipulated, stored, and presented by a database.
Typical operations on a data structure are

ADD
INSERT
DELETE or REMOVE
FIRST
NEXT
LAST
LOCATE

STACK
A LIST is a very general computer data structure. However, there are
certain type of the list that are so common, they are given their own
name. The STACK is a last-in First-Out (LIFO) list. Only the last item in
the stack can be accessed directly. If you had a number of items added

2 | Page
Structure.

Data

to a stack in this order 1.'Dog' 2.'Cat' 3.'Horse', the stack would look like
this

The standard operations on a stack are


Horse (last in)
PUSH
POP
TOP

Cat
Adds an itemdog
to the
top
(first in)of the stack
Removes an item from the top of the stack
identifies the item at the top of the stack, but does not remove
it

QUEUE
The QUEUE is another extremely common type of list data structure.
A queue is a First-In, First-Out.
A queue maintains two pointers
1. A front of queue pointer
2. An end of queue pointer

Uses of a queue
A queue data structure is used whenever there are a number of items
waiting for a resource to become available. If you had three items added

3 | Page
Structure.

Data

to queue in the order 1.'Dog' 2.'Cat' 3.'Horse' the queue would look like
this

The start pointer locates 'dog' and the rear pointer locates 'horse'

Dog
Cat
Horse

Operations on a Queue
ADD
REMOVE

Add an time to the back of the queue


Removes the item at the front of the queue, but does not

FRONT

remove it
Identifies the item at the front of the queue. but does not
remove it

There are three types of queue


Printer queue
Process queue
A simulation queue

TREE

4 | Page
Structure.

Data

The QUEUE and the STACK are linear lists. This mean each data item
only points to the one before it and after it. They have the idea of order
built into them, such as 'last' or 'first'. But they do not imply there is any
relationship between the data items themselves. The TREE on the other
hand, is designed to represent the relationship between data items
Just like a family tree, a TREE data structure is illustrated below

Each data item within a tree is called a 'node'.


The highest data item in the tree is called the 'root' or root mode.
Below the root lie a number of other 'nodes'. The root is the 'parent'
of the nodes immediately linked to it and these are the 'children' of
the parent node.
If nodes share a common parent, then they are 'sibling' nodes, just
like a family.
The link joining one node to another is called the 'branch'
The tree structure above is a general tree.

5 | Page
Structure.

Data

Operations of the tree


CREATE
LEFT
RIGHT
ITEM
EMPTY TREE
INSERT
DELETE

Create a new tree


Get the left sub-tree
Get the right sub-tree
Get the data item within the root node
Informs whether or not the tree is empty
Place a node at a specific location within their tree
remove a node from a specific location within the tree

Root Node
Node at the "top" of a tree - the one from which all operations on the tree
commence. The root node may not exist (a NULL tree with no nodes in
it) or have 0, 1 or 2 children in a binary tree.
Leaf Node
Node at the "bottom" of a tree - farthest from the root. Leaf nodes have
no children.
Complete Tree
Tree in which each leaf is at the same distance from the root. A more
precise and formal definition of a complete tree is set out later.
Height
Number of nodes which must be traversed from the root to reach a leaf
of a tree.

1.2 explain the operation and performance of sorting and search


algorithms.

6 | Page
Structure.

Data

The quick sort uses divide and conquer to gain the same advantages
as the merge sort, while not using additional storage. As a trade-off,
however, it is possible that the list may not be divided in half. When this
happens, we will see that performance is diminished.
A quick sort first selects a value, which is called the pivot value.
Although there are many different ways to choose the pivot value, we will
simply use the first item in the list. The role of the pivot value is to assist
with splitting the list. The actual position where the pivot value belongs in
the final sorted list, commonly called the split point, will be used to
divide the list for subsequent calls to the quick sort.
Figure 12 shows that 54 will serve as our first pivot value. Since we have
looked at this example a few times already, we know that 54 will
eventually end up in the position currently holding 31. The partition
process will happen next. It will find the split point and at the same time
move other items to the appropriate side of the list, either less than or
greater than the pivot value.

Figure 12: The First Pivot Value for a Quick Sort

The Binary Search


It is possible to take greater advantage of the ordered list if we are clever
with our comparisons. In the sequential search, when we compare
against the first item, there are at most n-1
more items to look through if the first item is not what we are looking for.
Instead of searching the list in sequence, a binary search will start by
examining the middle item. If that item is the one we are searching for,
we are done. If it is not the correct item, we can use the ordered nature
of the list to eliminate half of the remaining items. If the item we are
searching for is greater than the middle item, we know that the entire

7 | Page
Structure.

Data

lower half of the list as well as the middle item can be eliminated from
further consideration. The item, if it is in the list, must be in the upper
half.
We can then repeat the process with the upper half. Start at the middle
item and compare it against what we are looking for. Again, we either
find it or split the list in half, therefore eliminating another large part of
our possible search space. Figure 3 shows how this algorithm can
quickly find the value 54. The complete function is shown in CodeLens 3.

Figure 3: Binary Search of an Ordered List of Integers

1.3 explain the operation of recursive algorithms and identify


situations when recursion is used .
A recursive algorithm is an algorithm which calls itself with "smaller (or
simpler)" input values, and which obtains the result for the current input
by applying simple operations to the returned value for the smaller (or
simpler) input. More generally if a problem can be solved utilizing
solutions to smaller versions of the same problem, and the smaller
versions reduce to easily solvable cases, then one can use a recursive
algorithm to solve that problem. For example, the elements of a
recursively defined set, or the value of a recursively defined function can
be obtained by a recursive algorithm.
If a set or a function is defined recursively, then a recursive algorithm to
compute its members or values mirrors the definition. Initial steps of the
recursive algorithm correspond to the basis clause of the recursive
definition and they identify the basis elements. They are then followed by
steps corresponding to the inductive clause, which reduce the
computation for an element of one generation to that of elements of the
immediately preceding generation.

8 | Page
Structure.

Data

In general, recursive computer programs require more memory and


computation compared with iterative algorithms, but they are simpler and
for many cases a natural way of thinking about the problem.
Example 1: Algorithm for finding the k-th even natural number
Note here that this can be solved very easily by simply outputting 2*(k 1) for a given k . The purpose here, however, is to illustrate the basic
idea of recursion rather than solving the problem.
Algorithm 1: Even(positive integer k)
Input: k , a positive integer
Output: k-th even natural number (the first even being 0)
Algorithm:
if k = 1, then return 0;
else return Even(k-1) + 2 .
Here the computation of Even(k) is reduced to that of Even for a smaller
input value, that is Even(k-1). Even(k) eventually becomes Even(1)
which is 0 by the first line. For example, to compute Even(3), Algorithm
Even(k) is called with k = 2. In the computation of Even(2), Algorithm
Even(k) is called with k = 1. Since Even(1) = 0, 0 is returned for the
computation of Even(2), and Even(2) = Even(1) + 2 = 2 is obtained.
This value 2 for Even(2) is now returned to the computation of Even(3),
and Even(3) = Even(2) + 2 = 4 is obtained.
As can be seen by comparing this algorithm with the recursive definition
of the set of nonnegative even numbers, the first line of the algorithm
corresponds to the basis clause of the definition, and the second line
corresponds to the inductive clause.
By way of comparison, let us see how the same problem can be solved
by an iterative algorithm.
Algorithm 1-a: Even(positive integer k)
Input: k, a positive integer
Output: k-th even natural number (the first even being 0)
Algorithm:
int i, even;
i := 1;
even := 0;
while( i < k ) {
even := even + 2;

9 | Page
Structure.

Data

i := i + 1;
}
return even .

Task 2
2.1 implement data structures in an executable programming
language in the context of well-defined problems

Searching
Linear Search
#include<iostream.h>
#include<conio.h>

int lsearch(int Arr[], int s, int VAL);

int main()
{

10 | P a g e
Structure.

Data

int Arr[100],n,val,found;
cout<<"Enter number of elements you want to insert ";
cin>>n;
for(int i=0;i<n;i++)
{
cout<<"Enter element "<<i+1<<":";
cin>>Arr[i];
}

cout<<"Enter the number you want to search ";


cin>>val;

found=lsearch(Arr,n,val);

if(found==1)
cout<<"\nItem found";
else
cout<<"\nItem not found";

getch();
return 0;
}

11 | P a g e
Structure.

Data

int lsearch(int Arr[], int s, int VAL)


{
for(int I=0; I<s; I++)
{
if(Arr[I]==VAL)
return 1;
}
return 0;
}

Linear Searching Interface

Binary
Binary searching
#include<iostream.h>
#include<conio.h>
main()
{

12 | P a g e
Structure.

Data

int a[100],n,i,beg,end,mid,item;

cout<<"\n------------ BINARY SEARCH ------------ \n\n";


cout<<"Enter No. of Elements= ";
cin>>n;

cout<<"\nEnter Elements in Sorted Order=\n";


for(i=1;i<=n;i++)
{
cout<<"Enter Element "<<i<<" = ";
cin>>a[i];
}

cout<<"\nEnter Item you want to Search= ";


cin>>item;

beg=1;
end=n;

mid=(beg+end)/2;

while(beg<=end && a[mid]!=item)


{
if(a[mid]<item)
beg=mid+1;
else

13 | P a g e
Structure.

end=mid-1;

mid=(beg+end)/2;
}

if(a[mid]==item)
{
cout<<"\nData is Found at Location : "<<mid;
}
else
{
cout<<"Data is Not Found";
}
getch();
}

Binary Searching interface

Data

14 | P a g e
Structure.

Data

Sorting
Heap Sort
# include <iostream.h>
# include <conio.h>

main()
{
int a[50],size;
int p,c,i;
cout<<"Enter the Size of an Array :";
cin>>size;

cout<<"Enter Value of A[1] :";


cin>>a[1];
for(int i=2;i<=size;i++)
{
cout<<"Enter Value of A["<<i<<"] :";
cin>>a[i];
p=i/2;
c=i;
while(1)

15 | P a g e
Structure.

Data

{
if( a[c] > a[p])
{
int t=a[c];
a[c]=a[p];
a[p]=t;
}
c=p;
p=p/2;
if(p<1)
{
break;
}
}
}
cout<<endl<<"Heap ..."<<endl;
for(i=1;i<=size;i++)
{
cout<<endl;
cout<<"Arr["<<i<<"] :"<<a[i];
}

int j=size;
int lc,rc;
while(j>1)
{
if(a[1] > a[j])

16 | P a g e
Structure.

Data

{
int t=a[1];
a[1]=a[j];
a[j]=t;
j--;
}
else
{
j--;
continue;
}

p=1;
while(p < j)
{
lc=p*2;
rc=p*2 + 1;
if(lc>=j || rc >=j)
{
break;
}
if(a[p] < a[lc] && a[lc] > a[rc])
{
int temp=a[lc];
a[lc]=a[p];
a[p]=temp;
p=lc;

17 | P a g e
Structure.

Data

}
else if (a[p] < a[rc] && a[rc] > a[lc])
{
int temp=a[rc];
a[rc]=a[p];
a[p]=temp;
p=rc;
}
else
{
break;
}
}
}

cout<<endl<<"Sorted List ..."<<endl;


for(i=1;i<=size;i++)
{
cout<<endl;
cout<<"Arr["<<i<<"] :"<<a[i];
}

getch();
}

Heap Sort Interface

18 | P a g e
Structure.

Data

Quick Sort
#include <iostream.h>
#include <conio.h>

main()
{
void srt(int[],int,int);
int a[10],count=0,n;

cout<<"Ener 10 values in unsorted order : \n";


for (n=0;n<10;n++)
{
cout<<"value no.: "<<(n+1)<<"\t";
cin>>a[n];
count++;
}

19 | P a g e
Structure.

Data

n=0;
srt(a,n,count-1);
cout<<"\t\tThe Sorted order is : \n";
for (n=0;n<10;n++)
{
cout<<"\t\tposition : "<<(n+1)<<"\t"<<a[n]<<"\n";
}
getch();
}
void srt(int k[20],int lb,int ub)
{
int i,j,key,flag=0,temp;
if (lb<ub)
{
i=lb;
j=ub+1;
key=k[i];
while(flag!=1)
{
i++;
while(k[i]<key)
{
i++;
}
j--;

20 | P a g e
Structure.

Data

while(k[j]>key)
{
j--;
}
if (i<j)
{
temp=k[i];
k[i]=k[j];
k[j]=temp;
}
else
{
flag=1;
temp=k[lb];
k[lb]=k[j];
k[j]=temp;
}
}
srt(k,lb,j-1);
srt(k,j+1,ub);
}
}

21 | P a g e
Structure.

Quick Sort Interface

Data

22 | P a g e
Structure.

Data

Binary Search
1. Coding
#include<iostream.h>
#include<conio.h>
void search(int a[], int beg, int end, int item)

// Function to Search

Element
{
if(beg==end)

// if Single Element is in the List

{
if(item==a[beg])
cout<<"\nThe Element is Found at Position : "<<beg;
else
cout<<"\nData is Not Found";
}

else

23 | P a g e
Structure.

Data

{
int mid = (beg + end)/2;
if(item == a[mid])
cout<<"\nThe Element is Found at Position : "<<mid;

else if(item < a[mid])


search(a,beg,mid-1,item);

// Function Calls Itself (Recursion)

else
search(a,mid+1,end,item);
}

main()
{

// Function Calls Itself (Recursion)

24 | P a g e
Structure.

Data

int a[100],item,n,beg,end,mid,loc;
cout<<"\n------- Binary Search using Recursion -------\n\n";
cout<<"Enter the number of Elements : ";
cin>>n;

cout<<"\nEnter the elements :\n";


for(loc=1;loc<=n;loc++)
{
cin>>a[loc];
}
cout<<"\nEnter the Element to be searched : ";
cin>>item;

beg=1;
end=n;

search(a,beg,end,item);

// Function Call in Main Function

25 | P a g e
Structure.

Data

getch();
}
2. Interface

2.2 implement opportunities for error handling and reporting

Error Handling
1. Undeclared Variables
int main()
{
cin>>x;
cout<<x;
}
"Huh? Why do I get an error?"
Your compiler doesn't know what x means. You need to declare it
as a variable.
int main()
{

26 | P a g e
Structure.

Data

int x;
cin>>x;
cout<<x;
}
2. Using a single equal sign to check equality
char x='Y';
while(x='Y')
{
//...
cout<<"Continue? (Y/N)";
cin>>x;
}

"Why doesn't my loop ever end?"


If you use a single equal sign to check equality, your program will
instead assign the value on the right side of the expression to the
variable on the left hand side, and the result of this statement is the
value assigned. In this case, the value is 'Y', which is treated as
true. Therefore, the loop will never end. Use == to check for
equality; furthermore, to avoid accidental assignment, put variables
on the right hand side of the expression and you'll get a compiler
error if you accidentally use a single equal sign as you can't assign
a value to something that isn't a variable.
char x='Y';
while('Y'==x)
{
//...
cout<<"Continue? (Y/N)";

27 | P a g e
Structure.

Data

cin>>x;
}
3. Extra Semicolons
int x;
for(x=0; x<100; x++);
cout<<x;

"Why does it output 100?"


You put in an extra semicolon. Remember, semicolons don't go
after if statements, loops, or function definitions. If you put one in
any of those places, your program will function improperly.
int x;
for(x=0; x<100; x++)
cout<<x;

4. Semi colon Expected


int x
for(x=0; x<100; x++)
cout<<x
Program will not be start if u lack of semi colon in necessary place
int x;
for(x=0; x<100; x++)
cout<<x;

5. Missing Terminating Character (" Expected)

28 | P a g e
Structure.

Data

int a, b;
int sum;
cout<<Enter two numbers to add: ;
cin>>b;
cin>>a;
sum=a+b;
cout<<The sum is: <<sum;
Remember! If you don't put " in necessary place you compiler will
keep saying Missing Terminating " Expected
int a, b;
int sum;
cout<<"Enter two numbers to add: ";
cin>>b;
cin>>a;
sum=a+b;
cout<<"The sum is: "<<sum;

6. Curly Bracket Expected


int main()
cin>>x;
cout<<x;

If u don't put curly bracket in necessary place your program will


function improperly.
int main()
{
cin>>x;

29 | P a g e
Structure.

Data

cout<<x;}

2.3 test result to enable comparison with expected results

Meaning of coding
#include <iostream>
#include <cstdlib>
using namespace std;
main()
{
int i,c;
cout<<"Enter Number!"<<endl; //Show "Enter
number" in command prompt//
cin>>i; //put user enter number into int i//
for(int l=2; l<=12; l++) //looping for 11 times untill l
reach 12//
{
if(i/l==0 ) //if int i divide int l equal 0
{
if(i!=2 && i!=3) //if int i not equal 2 and int i
not eqal 3 the program command line in ( } will work , if not
will go to next phase
{
cout<<"This number is not prime
number \n"; //show "This number is not prime number in
command prompt"
}
else //if first condition doesn't work out ,
else command line will excute

30 | P a g e
Structure.

Data

{
cout<<"this number is prime \n";
//show "Enter
}
}
else if(i/l!=0) //if first condition doesn't work out ,
int i divide int l == 0 condition will test
{
cout<<"This number is prime \n"; //show
"this number is prime in command prompt"
}
exit(0);

//exit

cout<<"Program will excute !"<<endl; //show "Program


will excute in command prompt
exit(0); //exit
cout<<"Program will never excute"<<endl; //show
"Program will excute in command prompt
}

Test result of a program


#include <iostream>
using namespace std;
class distances
{

31 | P a g e
Structure.

Data

private: int feet,inches;


public:
distances()
{
feet=0;
inches=0;
}
void get_data()
{
cout<<"Enter Feet!!";
cin>>feet;
cout<<"enter inches!!";
cin>>inches;
}
distances add_data(distances d1, distances d2)
{
distances temp,temp1;
temp.inches=d1.inches + d2.inches;
temp.feet=d1.feet + d2.feet;
if(temp.inches >= 12)
{
temp.feet+=temp.inches/12;
temp1.inches=temp.inches%12;
}
temp1.feet=temp.feet;
return temp1;

32 | P a g e
Structure.

Data

}
void show_data()
{
cout<<feet<<" feet "<<inches<<" inches "<<endl;
}
};
main()
{
distances dd,ee,ff,temp2;
dd.get_data();
ee.get_data();
temp2 = ff.add_data(dd,ee);
temp2.show_data();
}

Interface of a program

Task 3

33 | P a g e
Structure.

Data

3.1 explain common string operations and their practical


applications

String Operation and their particular Applications


String :: c_str
Returns a pointer to an array that contains a null-terminated sequence of
characters (i.e a C string) representing the current value of the string
object.
This array includes the same sequence of characters that make up the
value of string object plus an additional terminating null-character ('\0') at
the end.

I.

Example Coding

#include <iostream>
#include <cstring>
#include <string>

int main ()
{
std::string str ("Hit me into pieces");

char * cstr = new char [str.length()+1];


std::strcpy (cstr, str.c_str());

char * p = std::strtok (cstr," ");


while (p!=0)
{
std::cout << p << '\n';
p = strtok(NULL," ");

34 | P a g e
Structure.

Data

delete[] cstr;
return 0;
}

II.

Interface

String :: copy
Copies a substring of the current value of the string object into the array
pointed by s. This substring contains the len characters that tart at
position pos.
This function does not append a null character at the end of the copied
content
s

Pointer to an array of characters. The array shall contain


enough storage for the copied characters.

len

number of characters to copy (if the string is shorter, as


many characters as possible are copied)

pos
postion

postion of the first character to be copied. if this is greater


than the string length, it throws out of range. note:: the first
character in the string is denoted by a value of 0 not 1

I.

Example Coding

#include <iostream>
#include <string>

35 | P a g e
Structure.

Data

int main ()
{
char buffer[20];
std::string str ("Test string...");
std::size_t length = str.copy(buffer,6,5);
buffer[length]='\0';
std::cout << "buffer contains: " << buffer << '\n';
return 0;
}

II.

Interface

string: find
Searches the string for the first occurrence of the sequence specified by
its arguments. When pos is specified, the search only includes
characters at or after position pos, ignoring any possible occurrences
that include characters before pos. Notice that unlike member
find_first_of, whenever more than one character is being searched for, it
is not enough that just one of these characters match, but the entire
sequence must match.

Parameter
str

Another string with the subject to search for.

pos

Position of the first character in the string to be considered in


the search.

36 | P a g e
Structure.

Data

If this is greater than the string length, the function never


finds matches.
Note: The first character is denoted by a value of 0 (not 1): A
value of 0 means that the entire string is searched.
s

Pointer to an array of characters.


If argument n is specified (3), the sequence to match are the
first n characters in the array.
Otherwise (2), a null-terminated sequence is expected: the
length of the sequence to match is determined by the first
occurrence of a null character.

Length of sequence of characters to match.

Individual character to be searched for.


I.

Example Coding

#include <iostream>
#include <string>

int main ()
{
std::string str ("There are two nouns in this sentence with nouns.");
std::string str2 ("noun");
std::size_t found = str.find(str2);
if (found!=std::string::npos)
std::cout << "first 'noun' found at: " << found << '\n';

found=str.find("noun are small",found+1,6);


if (found!=std::string::npos)
std::cout << "second 'noun' found at: " << found << '\n';

37 | P a g e
Structure.

Data

found=str.find("sentence");
if (found!=std::string::npos)
std::cout << "'sentence' also found at: " << found << '\n';

found=str.find('.');
if (found!=std::string::npos)
std::cout << "Period found at: " << found << '\n';

str.replace(str.find(str2),str2.length(),"preposition");
std::cout << str << '\n';

return 0;
}

II.

Interface

String :: rfind
Searches the string for the last occurrence of the sequence specified by
its arguments. When pos is specified, the search only included
sequences of characters that begin at or before position pos, ignoring
any possible match beginning after pos

38 | P a g e
Structure.

Data

Str

Another string with the subject to search for.

pos

Position of the last character in the string to be considered as


the beginning of a match.
Any value greater or equal than the string length (including
string::npos) means that the entire string is searched.
Note: The first character is denoted by a value of 0 (not 1).

Pointer to an array of characters.


If argument n is specified (3), the sequence to match are the
first n characters in the array.
Otherwise (2), a null-terminated sequence is expected: the
length of the sequence to match is determined by the first
occurrence of a null character.

Length of sequence of characters to match.

Individual character to be searched for.

I.

Example Coding

#include <iostream>
#include <string>

int main ()
{
std::string str ("I Hate You !");
std::string key ("Hate");

unsigned found = str.rfind(key);


if (found!=std::string::npos)
str.replace (found,key.length(),"love");

39 | P a g e
Structure.

Data

std::cout << str << '\n';

return 0;
}

II.

Interface

String :: find_first_of
Searches the string for the first character that matches any of the
characters specified in its arguments. When pos is specified, the search
only includes characters at or after position pos, ignoring any possible
occurrences before pos. Notice that it is enough for one single character
of the sequence to match (not all of them). See string::find for a function
that matches entire sequences.

Parameters
Str

Another string with the characters to search for.

Pos

Position of the first character in the string to be considered in


the search.
If this is greater than the string length, the function never
finds matches.
Note: The first character is denoted by a value of 0 (not 1): A
value of 0 means that the entire string is searched.

Pointer to an array of characters. If argument n is specified


(3), the first n characters in the array are searched for.
Otherwise (2), a null-terminated sequence is expected: the
length of the sequence with the characters to match is

40 | P a g e
Structure.

Data

determined by the first occurrence of a null character.


N

Number of character values to search for.

Individual character to be searched for.

I.

Example Coding

#include <iostream>
#include <string>
#include <cstddef>

int main ()
{
std::string str ("The vowels in this sentense gonna replace by
asterisks.");
std::size_t found = str.find_first_of("aeiou");
while (found!=std::string::npos)
{
str[found]='*';
found=str.find_first_of("aeiou",found+1);
}

std::cout << str << '\n';

return 0;
}

41 | P a g e
Structure.

II.

Data

Interface

String :: substr
Returns a newly constructed string object with its value initialized to a
copy of a substring of this object. The substring is the portion of the
object that starts at character position pos and spans len characters (or
until the end of the string, whichever comes first).

Parameters
pos

Position of the first character to be copied as a substring.


If this is equal to the string length, the function returns an
empty string.
If this is greater than the string length, it throws out_of_range.
Note: The first character is denoted by a value of 0 (not 1).

len

Number of characters to include in the substring (if the string


is shorter, as many characters as possible are used).
A value of string :: npos indicates all characters until the end
of the string.

I.

Example Coding

#include <iostream>
#include <string>

42 | P a g e
Structure.

Data

int main ()
{
std::string str="We think in generalities, but we live in details.";

std::string str2 = str.substr (12,12);

unsigned pos = str.find("live");

std::string str3 = str.substr (pos);


std::cout << str2 << ' ' << str3 << '\n';

return 0;
}

II.

Interface

Task 4
3.2 demonstrate the outcome of string operations in specified
algorithm
Outcome of a string operation
I.

Example Code

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

43 | P a g e
Structure.

int compare_string(char*, char*);


int string_ln(char*);
int main()
{
char str[20];
int length;

printf("\nEnter any string : ");


gets(str);
length = string_ln(str);
printf("The length of the given string %s is : %d", str, length);
getch();
char first[100], second[100], result;
printf("\nEnter first string\n");
gets(first);
printf("Enter second string\n");
gets(second);
result = compare_string(first, second);
if ( result == 0 )
printf("Both strings are same.\n");

Data

44 | P a g e
Structure.

else
printf("Entered strings are not equal.\n");
return 0;
}
int string_ln(char*p) /* p=&str[0] */
{
int count = 0;
while (*p != '\0') {
count++;
p++;
}
return count;
}
int compare_string(char *first, char *second)
{
while(*first==*second)
{
if ( *first == '\0' || *second == '\0' )
break;
first++;
second++;
}
if( *first == '\0' && *second == '\0' )
return 0;

Data

45 | P a g e
Structure.

else
return -1;
}
II.

Interface of an outcome string operation

Data

You might also like