You are on page 1of 94

2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY


Department of Computer Science and Engineering
2​nd ​Year 1​st​ Semester

Python Programming Lab (2017-18)

R16

Lab Manual

1​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

Python programming lab:

Experiment Topics TITILE DATE PAGE_NO


No
a)
Running instructions in Interactive
interpreter and a Python Script
1 Basics 16-06-2017
6
b)
Write a program to purposefully raise
Indentation Error and Correct it
6
a)
Write a program to compute distance
between two points taking input from
2 Operations the user 16-06-2017 6
(Pythagorean Theorem)
b)
Write a program add.py that takes 2
numbers as command line arguments
and prints its sum. 7
a)
Write a Program for checking
whether the given number is a even
number or not. 7
b)
Using a for loop, write a program
3 Control Flow that prints out the decimal 22-06-2017
equivalents of 1/2, 1/3, 1/4, . . . , 8
1/10
c)
Write a program using a for loop that
loops over a sequence. What is
sequence? 8
d)
Write a program using a while loop
that asks the user for a number, and
prints a countdown from that number 9
to zero.
a)
Find the sum of all the primes below
two million.
Each new term in the Fibonacci 10
sequence is generated by adding the
Control Flow -  previous two terms. By
4 Continued  23-06-2017

2​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

starting with 1 and 2, the first 10


terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
b)
By considering the terms in the
Fibonacci sequence whose values do
not exceed four million, 10
find the sum of the even-valued
terms.

a)
Write a program to count the
numbers of characters in the string 11
and store them in a dictionary data 30-06-2017
5 DS  structure
b)
Write a program to use split and join
methods in the string and trace a
birthday with a dictionary data 12
structure.
a)
Write a program combine_lists that
combines these lists into a dictionary.
30-06-2017 12
b)
6  DS - Continued Write a program to count frequency
of characters in a given file. Can you
use character frequency to tell 13
whether the given file is a Python
program file, C program file or a text
file?
a)
Write a program to print each line of
a file in reverse order.
7  Files 
06-07-2017 13
b)
Write a program to compute the
number of characters, words and
lines in a file. 14
a)
Write a function ball_collide that
takes two balls as parameters and
computes if they are colliding. Your 14
function should return a Boolean
representing whether or not the balls
8 Functions are colliding. 13-07-2017
Hint: Represent a ball on a plane as a
tuple of (x, y, r), r being the radius

3​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

If (distance between two balls


centers) <= (sum of their radii) then
(they are colliding)
b)
Find mean, median, mode for the
given set of numbers in a list.
15
a)
Write a function nearly_equal to test
whether two strings are nearly equal.
Two strings a and b are nearly equal 15
when a can be generated by a single
mutation on b. 20-07-2017
9 Functions  b)
-Continued Write a function dups to find all
duplicates in the list.
16
c)
Write a function unique to find all
the unique elements of a list.
16
a)
Write a function cumulative_product
to compute cumulative product of a
list of numbers. 17
b)
Functions -  Write a function reverse to reverse a 27-07-2017
10
Problem  list. Without using the reverse
Solving function. 18
c)
Write function to compute gcd, lcm
of two numbers. Each function
shouldn’t exceed one line. 18
a)
Write a program that defines a matrix
and prints
03-08-2017 18
11 Multi-D Lists b)
Write a program to perform addition
of two square matrices
19
c)
Write a program to perform
multiplication of two square matrices
20

4​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

a)
Install packages requests, flask and
explore them. using (pip)
12 Modules 24-08-2017 21
b)
Write a script that imports requests
and fetch content from the page. Eg.
(Wiki) 24
c)
Write a simple script that serves a
simple HTTPResponse and a simple
HTML Page 26
a)
Class variables and instance variable
13 OOP i) Robot 31-08-2017
ii) ATM Machine 34
1.
Write a GUI for an Expression
Calculator using tk
38
14 GUI, 2.
Write a program to implement the 08-09-2017
Graphics following figures using turtle
40

a)
Write a test-case to check the
function even_numbers which return
True on passing a list of all even 42
numbers 21-09-2017
15 Testing
b)
Write a test-case to check the
function reverse_string which returns
the reversed string. 42
a)
Build any one classical data
structure.
43
16 Advanced b) 21-09-2017
Write a program to solve knapsack
problem.
45

5​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

PYTHON PROGRAMMING PROGRAMES

1.
a. Running instructions in Interactive interpreter and a Python Script?
>>> 3+5

8
>>> 4-2

2
>>> 8/2

4.0

b. Write a program to purposefully raise Indentation Error and Correct it


n1=int(input("enter n1 value"))
n2=int(input("enter n2 value"))
if n1>n2:
print("n1 is big")
else:
print("n2 is big")

Output:
Error: Excepted an indented block
Correct Program:

n1=int(input("enter n1 value"))
n2=int(input("enter n1 value"))
if n1>n2:
print("n1 is big")
else:
print("n2 is big")
Output:
enter n1 value10
enter n1 value20
n2 is big

6​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

2.
a. Write a program to compute distance between two points taking input from the user
(Pythagorean Theorem)

import math;
x1=int(input("Enter x1--->"))
y1=int(input("Enter y1--->"))

x2=int(input("Enter x2--->"))
y2=int(input("Enter y2--->"))

d1 = (x2 - x1) * (x2 - x1);


d2 = (y2 - y1) * (y2 - y1);
res = math.sqrt(d1+d2)
print ("Distance between two points:",res);

Output:

Enter x1--->10
Enter y1--->20
Enter x2--->15
Enter y2--->19
Distance between two points: 5.0990195135927845

b. Write a program add.py that takes 2 numbers as command line arguments and prints
its sum.

step 1: open notepad and write the below program

import sys;
n1=int(sys.argv[1]);
n2=int(sys.argv[2]);
print (n1+n2)

step 2: SAVE

step 3: Open DOS SHELL and go to file saved location (D:\)

step 4: python filename.py argument1 argument2

Output:
python filename.py 10 20
30
3.
7​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

a. Write a Program for checking whether the given number is a even number or not.

n=int(input("Enter a number---->"))
if n % 2 == 0:
print ("EVEN Number");
else:
print ("ODD Number");

Output:

Enter a number---->10
EVEN Number

Enter a number---->11
ODD Number

b. Using a for loop, write a program that prints out the decimal equivalents of 1/2, 1/3,
1/4, . . . ,1/10

i=1;
for j in range(2,10):
print("i:",i,"j:",j)
print(i,"/",j)
print (i/j);

Output:

i: 1 j: 2
1/2
0.5
i: 1 j: 3
1/3
0.3333333333333333
i: 1 j: 4
1/4
0.25
i: 1 j: 5
1/5
0.2
i: 1 j: 6
1/6
0.16666666666666666
8​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

i: 1 j: 7
1/7
0.14285714285714285
i: 1 j: 8
1/8
0.125
i: 1 j: 9
1/9
0.1111111111111111

c. Write a program using a for loop that loops over a sequence. What is sequence ?

str="i am python developer"


for i in str:
print(i)

Output:

a
m

p
y
t
h
o
n

d
e
v
e
l
o
p
e
r

9​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

d. Write a program using a while loop that asks the user for a number, and prints a
countdown from that number to zero.

n = int(input("Enter A Number--->"));
while n >=0:
print (n);
n = n - 1;

Output:

Enter A Number--->10
10
9
8
7
6
5
4
3
2
1
0

4.
a. Find the sum of all the primes below two million.
Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89,...

a, b = 1, 2
total = 0
print(a,end=" ")
while (a <=2000000-1):
if a % 2 != 0:
total += a
a, b = b, a+b
print(a,end=" ")
print("\n sum of prime numbers term in fibonacci series: ",total)

Output:

10​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368
75025 121393 196418 317811 514229 832040 1346269 2178309
sum of prime numbers term in fibonacci series: 2435422

b. By considering the terms in the Fibonacci sequence whose values do not exceed four
million, find the sum of the even-valued terms.

a, b = 1, 2
total = 0
print(a,end=" ")
while (a <=4000000-1):
if a % 2 == 0:
total += a
a, b = b, a+b
print(a,end=" ")
print("\n sum of prime numbers term in fibonacci series: ",total)

Output:

1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368
75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887
sum of prime numbers term in Fibonacci series: 4613732

5.
a. Write a program to count the numbers of characters in the string and store them in a
dictionary data structure

str=input("Enter a String:")
dict = {}
for n in str:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
print (dict)

(OR)

str=input("Enter a String")
dict = {}
for i in str:

11​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

dict[i] = str.count(i)
print (dict)

Output:

Enter a String: guntur


{'g': 1, 'u': 2, 'n': 1, 't': 1, 'r': 1}

----------------------------------------------- (OR) -------------------------------------------

str=input("Enter a String")
dist={}
L=len(str);
d={str:L};
print(d)

​Output:

Enter a Stringguntur
{'guntur': 6}

b. Write a program to use split and join methods in the string and trace a birthday with
a dictionary data structure.
a="hi i am python programmer"
b=a.split()
print (b)
c=" ".join(b)
print(c)

Output:

['hi', 'i', 'am', 'python', 'programmer']


hi i am python programmer

6.
a. Write a program combine_lists that combines these lists into a dictionary.
l1=[1,2,'cse',4,5]
l2=['khit',7,'cse',9]
l=l1+l2
d={}
for i in range(len(l)):
d[i]=l[i]

12​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

print("The dictionary is------>",d)

Output:
The dictionary is------> {0: 1, 1: 2, 2: 'cse', 3: 4, 4: 5, 5: 'khit', 6: 7, 7: 'cse', 8: 9}

---------------------------------------------OR--------------------------------
l=[1,'python',4,7]
k=['cse',2,'guntur',8]
m=[]
m.extend(l);
m.extend(k);
print(m)
d={1:l,2:k,'combine_list':m}
print(d)

Output:

[1, 'python', 4, 7, 'cse', 2, 'guntur', 8]


{1: [1, 'python', 4, 7], 2: ['cse', 2, 'guntur', 8], 'combine_list': [1, 'python', 4, 7, 'cse', 2, 'guntur',
8]}
---------------------------------------------OR--------------------------------
l=[1,'python',4,7]
k=['cse',2,'guntur',8]
m=[]
m.append(l);
m.append(k);
print(m)
d={1:l,2:k,'combine_list':m}
print(d)

Output:

[[1, 'python', 4, 7], ['cse', 2, 'guntur', 8]]


{1: [1, 'python', 4, 7], 2: ['cse', 2, 'guntur', 8], 'combine_list': [[1, 'python', 4, 7], ['cse', 2, 'guntur',
8]]}

b. Write a program to count frequency of characters in a given file. Can you use
character frequency to tell whether the given file is a Python program file, C
program file or a text file?
import os
count =0
file=open("D:/a.txt")
for line in file:
for l in range(0,len(line)):
count+=1;
print("count:",count)
filename,file_extension=os.path.splitext("D:/a.txt");

13​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

print("file_extension==",file_extension);
if(file_extension=='.py'):
print("its python program file");
elif(file_extension==".txt"):
print("its a txt file");
elif(file_==extension==".c"):
print("its a c program file");

Output: ​a.txt contain “hi”

count: 2
file_extension== .txt
its a txt file
7.
a. ​Write a program to print each line of a file in reverse order.

input_file=open('D:/a.txt','r')
for line in input_file:
l=len(line)
s=' '
while(l>=1):
s=s+line[l-1]
l=l-1
print(s)
input_file.close()

a.txt file contain khit

Output:

tihk

b. ​Write a program to compute the number of characters, words and lines in a file.

k=open('D:/a.txt','r')
char,wc,lc=0,0,0
for line in k:
for k in range(0,len(line)):
char +=1
if(line[k]==' '):
wc+=1
if(line[k]=='\n'):
wc,lc=wc+1,lc+1

14​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

print("The no.of chars is %d\n The no.of words is %d\n The


no.of lines is %d"%(char,wc,lc))

a.txt contain

khit
Guntur
Hyderabad

Output:
The no. of chars is 21
The no. of words is 2
The no. of lines is 2

8.
a. Write a function ball_collide that takes two balls as parameters and computes if
they are colliding. Your function should return a Boolean representing whether or
not the balls are colliding.

Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the radius
If (distance between two balls centers) <= (sum of their radii) then (they are colliding)

import math
def ball_collide(x1,y1,r1,x2,y2,r2):
dist=math.sqrt((x2-x1)**2+(y2-y1)**2);
print("Distance b/w two balls:",dist)
center=dist/2;
print("Collision point",center);
r=r1+r2;
print("Sum of radious",r)
if(center<=r):
print("They are Colliding")
return True;
else:
print("Not Colliding")
return False;

c=ball_collide(4,4,3,2,2,3)
print(c)

15​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

c=ball_collide(100,200,20,200,100,10)
print(c)

Output:

Distance b/w two balls: 2.8284271247461903


Collision point 1.4142135623730951
Sum of radious 6
They are Colliding
True
Distance b/w two balls: 141.4213562373095
Collision point 70.71067811865476
Sum of radious 30
Not Colliding
False
b. Find mean, median, mode for the given set of numbers in a list.

from statistics import mean,median,mode


l = [15, 18, 2, 36, 12, 78, 5, 6, 9,18]
print("Mean",mean(l))
print("Median",median(l))
print("Mode",mode(l))

Output:

Mean 19.9
Median 13.5
Mode 18
9.
a. ​Write a function nearly_equal to test whether two strings are nearly equal. Two
strings a and b are nearly equal when a can be generated by a single mutation on
b.

from difflib import SequenceMatcher


def Nearly_Equal(a,b):
return SequenceMatcher(None,a,b).ratio();
a="khit"
b="khitc"
c=Nearly_Equal(a,b)
if(c*100>80):
print("Both Strings are similar")
print("a is mutation on b")

16​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

else:
print("Both Strings are Different")

Output:

Both Strings are similar


a is mutation on b

b. Write a function dups to find all duplicates in the list.

def FindDuplicates(list):

for i in list:
count = list.count(i)
if count > 1:
print ('There are duplicates in list')
return True
print ('There are no duplicates in list' )
return False

a = [8, 64, 16, 32, 4, 24]


b = [2,2,3,6,78,65,4,4,5]
print(a)
FindDuplicates(a)
print(b)
FindDuplicates(b)

Output:

[8, 64, 16, 32, 4, 24]


There are no duplicates in list
[2, 2, 3, 6, 78, 65, 4, 4, 5]
There are duplicates in list

c. ​Write a function unique to find all the unique elements of a list.

def FindUnique(list):
unique = set(list)
for i in unique:
count = list.count(i)
if count > 1:
print ('There are no unique elements in list')

17​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

return True
print ('There are unique elements in list' )
return False

a = [8, 64, 16, 32, 4, 24]


b = [2,2,3,6,78,65,4,4,5]
print(a)
FindUnique(a)
print(b)
FindUnique(b)

Output:

[8, 64, 16, 32, 4, 24]


There are unique elements in list
[2, 2, 3, 6, 78, 65, 4, 4, 5]
There are no unique elements in list
10.
a. Write a function cumulative_product to compute cumulative product of a list of
numbers.

def product(list):
p =1
for i in list:
p *= i
print(p)
return p
arr= [1,2,3,4,5,6,7,8,9,10]
c=product(arr)

Output:

1
2
6
24
120
720
5040
40320
362880
3628800

18​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

b. Write a function reverse to reverse a list. Without using the reverse function.

l = [1,2,3,4,5]
print (l[::-1])

Output:

[5, 4, 3, 2, 1]

c. Write function to compute gcd, lcm of two numbers. Each function shouldn’t
exceed one line.

import fractions
n1 = int(input("Enter n1 value:"))
n2 = int(input("Enter n2 value:"))
gcd = fractions.gcd(n1, n2)
print("GCD value is:",gcd)
def lcm(n, m):
return n * m / gcd

print("LCM value is:",int(lcm(n1,n2)))

Output:

Enter n1 value: 5
Enter n2 value: 9
GCD value is: 1
LCM value is: 45
11.
a. Write a program that defines a matrix and prints

row=int(input("Enter No of Rows for 1st Matrix:"))


column=int(input("Enter No of column for 1nd Matrix:"))
row1=int(input("Enter No of Rows for 2st Matrix:"))
column1=int(input("Enter No of column for 2nd Matrix:"))
X = [[int(input(("Enter value for X[",i,"][",j,"]:"))) for j
in range(column)] for i in range(row)]
Y = [[int(input(("Enter value for Y[",i,"][",j,"]:"))) for j
in range(column1)] for i in range(row1)]

19​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

print("1st Matrix X:",X)


print("2st Matrix Y:",Y)

Output:

Enter No of Rows for 1st Matrix: 3


Enter No of column for 1nd Matrix: 3
Enter No of Rows for 2st Matrix: 3
Enter No of column for 2nd Matrix: 3
('Enter value for X[', 0, '][', 0, ']:')5
('Enter value for X[', 0, '][', 1, ']:')8
('Enter value for X[', 0, '][', 2, ']:')2
('Enter value for X[', 1, '][', 0, ']:')1
('Enter value for X[', 1, '][', 1, ']:')9
('Enter value for X[', 1, '][', 2, ']:')2
('Enter value for X[', 2, '][', 0, ']:')3
('Enter value for X[', 2, '][', 1, ']:')4
('Enter value for X[', 2, '][', 2, ']:')5
('Enter value for Y[', 0, '][', 0, ']:')6
('Enter value for Y[', 0, '][', 1, ']:')0
('Enter value for Y[', 0, '][', 2, ']:')1
('Enter value for Y[', 1, '][', 0, ']:')4
('Enter value for Y[', 1, '][', 1, ']:')2
('Enter value for Y[', 1, '][', 2, ']:')5
('Enter value for Y[', 2, '][', 0, ']:')6
('Enter value for Y[', 2, '][', 1, ']:')7
('Enter value for Y[', 2, '][', 2, ']:')8
1st Matrix X: [[5, 8, 2], [1, 9, 2], [3, 4, 5]]
2st Matrix Y: [[6, 0, 1], [4, 2, 5], [6, 7, 8]]

b. ​Write a program to perform addition of two square matrices

row=int(input("Enter No of Rows for 1st Matrix:"))


column=int(input("Enter No of column for 1nd Matrix:"))
row1=int(input("Enter No of Rows for 2st Matrix:"))
column1=int(input("Enter No of column for 2nd Matrix:"))
X = [[int(input(("Enter value for X[",i,"][",j,"]:"))) for j
in range(column)] for i in range(row)]
Y = [[int(input(("Enter value for Y[",i,"][",j,"]:"))) for j
in range(column1)] for i in range(row1)]
print("1st Matrix X:",X)
print("2st Matrix Y:",Y)
if (row==row1 and column==column1):

20​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

result = [[X[i][j] + Y[i][j] for j in range(len(X))] for


i in range(len(X[0]))]
print(result)
else:
print("Adition 2 Matrix not Possible")

Output:

Enter No of Rows for 1st Matrix: 2


Enter No of column for 1nd Matrix: 2
Enter No of Rows for 2st Matrix: 2
Enter No of column for 2nd Matrix: 2
('Enter value for X[', 0, '][', 0, ']:')1
('Enter value for X[', 0, '][', 1, ']:')2
('Enter value for X[', 1, '][', 0, ']:')3
('Enter value for X[', 1, '][', 1, ']:')4
('Enter value for Y[', 0, '][', 0, ']:')5
('Enter value for Y[', 0, '][', 1, ']:')6
('Enter value for Y[', 1, '][', 0, ']:')7
('Enter value for Y[', 1, '][', 1, ']:')8
1st Matrix X: [[1, 2], [3, 4]]
2st Matrix Y: [[5, 6], [7, 8]]
[[6, 8], [10, 12]]

c. ​Write a program to perform multiplication of two square matrices

row=int(input("Enter No of Rows for 1st Matrix:"))


column=int(input("Enter No of column for 1nd Matrix:"))
row1=int(input("Enter No of Rows for 2st Matrix:"))
column1=int(input("Enter No of column for 2nd Matrix:"))
if(column==row1):
X = [[int(input(("Enter value for X[",i,"][",j,"]:"))) for
j in range(column)] for i in range(row)]
Y = [[int(input(("Enter value for Y[",i,"][",j,"]:"))) for
j in range(column1)] for i in range(row1)]
result = [[0 for j in range(column1)] for i in range(row)]
print("result",result)
​ rint("1st Matrix X:",X)
p
print("2st Matrix Y:",Y)
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]

for r in result:
print(r)

21​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

else:
print("Multiplication is not possible")

Output:

Enter No of Rows for 1st Matrix:2


Enter No of column for 1nd Matrix:2
Enter No of Rows for 2st Matrix:2
Enter No of column for 2nd Matrix:2
('Enter value for X[', 0, '][', 0, ']:')4
('Enter value for X[', 0, '][', 1, ']:')3
('Enter value for X[', 1, '][', 0, ']:')5
('Enter value for X[', 1, '][', 1, ']:')6
('Enter value for Y[', 0, '][', 0, ']:')2
('Enter value for Y[', 0, '][', 1, ']:')1
('Enter value for Y[', 1, '][', 0, ']:')7
('Enter value for Y[', 1, '][', 1, ']:')3
result [[0, 0], [0, 0]]
1st Matrix X: [[4, 3], [5, 6]]
2st Matrix Y: [[2, 1], [7, 3]]
[29, 13]
[52, 23]

12.

a. ​Install packages requests, flask and explore them. using (pip)


1. Open CMD and go to python installation path i.e [C:\Users\KHIT.khit
PC\AppData\Local\Programs\Python\Python36\Scripts]

22​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

2. Now install pip using easy_install

23​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

3. Check pip installed or not

24​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

4. Now install requests

25​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

5. Install flask

6. Install virtualenv

26​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

b. Write a script that imports requests and fetch content from the page. Eg. (Wiki)
I. First you need to install Wikipedia

27​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

After you run this code

import wikipedia

print(wikipedia.summary("wikipedia"))
wikipedia.search("branch")
ny=wikipedia.page("new york")
ny.title
ny.url
ny.contentny.links[0]
wikipedia.set.long["for"]
wikipedia.summaru("facebook",sentences=1)

Output:
Wikipedia ( ( listen) WIK-i-PEE-dee-ə or ( listen) WIK-ee-PEE-dee-ə) is a free online
encyclopedia with the aim to allow anyone to edit articles. Wikipedia is the largest and most
popular general reference work on the Internet, and is ranked the fifth-most popular website.
Wikipedia is owned by the nonprofit Wikimedia Foundation.

Wikipedia was launched on January 15, 2001, by Jimmy Wales and Larry Sanger. Sanger coined
its name, a portmanteau of wiki and encyclopedia…………………………

wikipedia.exceptions.DisambiguationError: "New York" may refer to:

New York (state)

New York City

28​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

New York, Lincolnshire

New York, North Yorkshire

New York, Tyne and Wear

New York metropolitan area

Manhattan

Province of New York

East New York, Brooklyn

West New York, New Jersey

New York, Florida

New York, Iowa

c. Write a simple script that serves a simple HTTPResponse and a simple HTML Page

I. install django

29​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

II. django-admin startproject helloapp

Running this command creates a skeleton django app with the following structure:
helloapp
├─helloapp
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py

30​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

III. move to helloapp

IV. create your own app

python manage.py startapp howdy

31​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

Running this command will create an app called howdy. Your file structure should
now look something like this.
helloapp
├── helloapp
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── howdy
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ ├── models.py
│ ├── tests.py
│ └── views.py
└── manage.py
V. now open settings.py in helloapp and change installed app to

# helloapp/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'howdy'
]

32​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

This was changed to

After save it.

VI.

33​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

let's run our server and see what will be output.


python manage.py runserver

If you look carefully, you will see a warning that you have unapplied migrations.
Ignore that for now. Go to your browser and access ​http://127.0.0.1:8000/​.

VII. Press control+break buttons you will come out from it.

34​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

VIII. Migrations make it easy for you to change your database schema (model)
without having to lose any data. Any time you create a new database model,
running migrations will update your database tables to use the new schema
without you having to lose any data or go through the tedious process of
dropping and recreating the database yourself.
python manage.py migrate

IX. Open urls.py in helloapp

# helloapp/urls.py
from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('howdy.urls')),
]

35​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

This was changed to

Save it
X. Now run server

python manage.py runserver

36​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

ModuleNotFoundError: No Module named ‘howdy.urls’

Let's fix that. Go to the ​howdy​ app folder and create a file called ​urls.py​.
The h​ owdy​ app folder should now look like this.
├── howdy
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ ├── __init__.py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py

Inside the new ​urls.py​ file, write this.


# howdy/urls.py
from django.conf.urls import url
from howdy import views

urlpatterns = [
url(r'^$', views.HomePageView.as_view()),
]

This code imports the views from our ​howdy​ app and expects a view
called ​HomePageView​ to be defined. Since we don't have one, open the ​views.py​ file in
the h​ owdy​ app and write this code.

37​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

# howdy/views.py
from django.shortcuts import render
from django.views.generic import TemplateView

# Create your views here.


class HomePageView(TemplateView):
def get(self, request, **kwargs):
return render(request, 'index.html', context=None)

This file defines a view called ​HomePageView​. Django views take in a ​request​ and
return a ​response​. In our case, the method ​get​ expects a HTTP GET request to the url
defined in our u​ rls.py​ file. On a side note, we could rename our method to p​ ost​ to
handle HTTP POST requests.
Once a HTTP GET request has been received, the method renders a template
called ​index.html​ which is just a normal HTML file which could have special Django
template tags written alongside normal HTML tags. If you run the server now, you
will see the following error page:

13.
a. ​Class variables and instance variable and illustration of the self variable
I. Robot

class Robot:
population=0
def __init__(self, name):
self.name = name
print('(Initializing {0})'.format(self.name))
Robot.population += 1
def __del__(self):
print('{0} is being destroyed!'.format(self.name))
Robot.population -= 1
if Robot.population == 0:
print('{0} was the last one.'.format(self.name))
else:
print('There are still {0:d} robots
working.'.format(Robot.population))
def sayHi(self):
print('Greetings, my masters call me
{0}.'.format(self.name))
def howMany():
print('We have {0:d}
robots.'.format(Robot.population))
howMany = staticmethod(howMany)
d=Robot('R1-D1')
d.sayHi()
Robot.howMany()

38​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

d1=Robot('R2-D2')
d1.sayHi()
Robot.howMany()
print("\nRobots can do some work here.\n")
print("Robots have finished their work. So let's destroy
them.")
del d
del d1
Robot.howMany()

Output:

(Initializing R1-D1)
Greetings, my masters call me R1-D1.
We have 1 robots.
(Initializing R2-D2)
Greetings, my masters call me R2-D2.
We have 2 robots.

Robots can do some work here.

Robots have finished their work. So let's destroy them.


R1-D1 is being destroyed!
There are still 1 robots working.
R2-D2 is being destroyed!
R2-D2 was the last one.
We have 0 robots.

II. ATM

class Bank:
Account_type = "Savings"
location = "Guntur"
def __init__(self, name, Account_Number,balance):
self.name = name
self.Account_Number = Account_Number
self.balance=balance
self.Account_type=Bank.Account_type
self.location=Bank.location

def __repr__(self):
print ("Welcome to the SBI ATM Machine ")
print("--------------------------------")
account_pin = int(input("Please enter your pin number
"))

39​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

if(account_pin==123):
Account(self)
else:
print("Pin Incorrect. Please try again")
Error(self)
return ' '.join([self.name,self.Account_Number])

def Error(self):

account_pin = int(input("Please enter your pin number "))


if(account_pin==123):
Account(self)
else:
print("Pin Incorrect. Please try again")
Error(self)
def Account(self):
print ("Your Card Number is:XXXX XXXX XXXX 1337")
print ("Would you like to deposit/withdraw/Check
Balance?")
print("""
1) Balance
2) Withdraw
3) Deposit
4) Quit

""")
option=int(input("Please enter your choice:"))
if(option==1):
Balance(self)
elif(option==2):
Withdraw(self)
elif(option==3):
Deposit(self)
elif(option==4):
exit()
def Balance(self):
print("Balance:",self.balance)
Account(self)
def Withdraw(self):
w=int(input("Please Enter Desired amount: "))
if(self.balance>0 and self.balance>=w):
self.balance=self.balance-w
print("Your transaction is successfull")
print("your Balance:",self.balance)
print("")
else:
print("Your transaction is cancelled due to")
print("Amount is not sufficient in your account")
Account(self)

40​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

def Deposit(self):
d=int(input("Please Enter Desired amount: "))
self.balance=self.balance+d
print("Your transaction is successfull")
print("Balance:",self.balance)
Account(self)
def Exit():
print ("Exit")
t1 = Bank('mahesh', 1453210145,5000)

print (t1)

Output:

Welcome to the SBI ATM Machine


--------------------------------
Please enter your pin number 12345
Pin Incorrect. Please try again
Please enter your pin number 123
Your Card Number is:XXXX XXXX XXXX 1337
Would you like to deposit/withdraw/Check Balance?

1) Balance
2) Withdraw
3) Deposit
4) Quit

Please enter your choice:1


Balance: 5000
Your Card Number is:XXXX XXXX XXXX 1337
Would you like to deposit/withdraw/Check Balance?

1) Balance
2) Withdraw
3) Deposit
4) Quit

Please enter your choice:2

41​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

Please Enter Desired amount: 1000


Your transaction is successfull
your Balance: 4000

Your Card Number is:XXXX XXXX XXXX 1337


Would you like to deposit/withdraw/Check Balance?

1) Balance
2) Withdraw
3) Deposit
4) Quit

Please enter your choice:3


Please Enter Desired amount: 100
Your transaction is successfull
Balance: 4100
Your Card Number is:XXXX XXXX XXXX 1337
Would you like to deposit/withdraw/Check Balance?

1) Balance
2) Withdraw
3) Deposit
4) Quit

Please enter your choice: 4

14.
a. Write a GUI for an Expression Calculator using tk.

import tkinter as tk
from tkinter import *

root = Tk()
buttons = {}
signVal = ''
firstVal = 1
root.title('Calculator')
root.attributes("-toolwindow", 1)

42​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

def createNumbers():
global buttons
buttonNum = 0
for b in range( 2 ):
for b2 in range( 5 ):
button = Button(frame2, text = buttonNum, font =
"Courier 9", width = 7, bd = 3 )
button.grid(row=b, column=b2)
buttons[ button ] = buttonNum
buttonNum += 1
button.bind( "<Button-1>", makeChoice )
def operators():
button = Button(frame2, text = '+', font = "Courier 9",
width = 5, bd = 3, command = lambda : operation('+') )
button.grid(row=2, column=0)
button = Button(frame2, text = '-', font = "Courier 9",
width = 5, bd = 3, command = lambda : operation('-') )
button.grid(row=2, column=1)
button = Button(frame2, text = '*', font = "Courier 9",
width = 5, bd = 3, command = lambda : operation('*') )
button.grid(row=2, column=2)
button = Button(frame2, text = '/', font = "Courier 9",
width = 5, bd = 3, command = lambda : operation('/') )
button.grid(row=2, column=3)
button = Button(frame2, text = '=', font = "Courier 9",
width = 5, bd = 3, command = lambda : excutionPart('=') )
button.grid(row=2, column=4)
button = Button(frame2, text = 'Clear', font = "Courier
9", width = 5, bd = 3, command = lambda : clearAll('clear') )
button.grid(row=3, column=0)
def makeChoice( event ):
global buttons
if (v.get() is None) or (len(v.get()) == 0):
v.set(buttons[ event.widget ])
else:
v.set(str(v.get())+str(buttons[ event.widget ]))
def operation(value):
try:
global signVal
global firstVal
signVal = value
if not isinstance(v.get(), int):
firstVal = int(v.get())
else:
tkMessageBox.showerror("Error","Wrong Formate")
print ("First Value :", firstVal)
v.set('')
except TypeError:
tkMessageBox.showerror("Error","Wrong Formate")
def excutionPart(ex):

43​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

print ("Second Value :", str(v.get()))


if signVal is '+':
v.set(int(firstVal)+int(v.get()))
elif signVal is '-':
v.set(int(firstVal)-int(v.get()))
elif signVal is '*':
v.set(int(firstVal)*int(v.get()))
elif signVal is '/':
v.set(int(firstVal)/int(v.get()))
else:
v.set('')
print ("Result is :", str(v.get()))
def clearAll(val):
v.set('')
frame1 = Frame(root)
frame1.pack(side = TOP)
#Bottom Frame
frame2 = Frame(root)
frame2.pack(side = BOTTOM)
v = StringVar()
e = Entry(frame1, textvariable=v, width = 3)
e.pack(side = LEFT)
createNumbers()
operators()
root.mainloop()

Output:

b. Write a program to implement the following figures using turtle

44​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

import turtle, random


colors =
["red","green","blue","orange","purple","pink","yellow"]
painter = turtle.Turtle()
painter.pensize(3)
for i in range(10):
color = random.choice(colors)
painter.pencolor(color)
painter.circle(100)
painter.right(30)
painter.left(60)
painter.setposition(0, 0)

Output:

import turtle

window = turtle.Screen()
window.bgcolor("lightgreen")

painter = turtle.Turtle()
painter.fillcolor('blue')

45​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

painter.pencolor('blue')
painter.pensize(3)

def drawsq(t, s):


for i in range(4):
t.forward(s)
t.left(90)

for i in range(1,180):
painter.left(18)
drawsq(painter, 200)

Output:

15.
a. Write a test-case to check the function even_numbers which return True on
passing a list of all even numbers

import unittest
def even_numbers(ls):
i=0
for i in range(len(ls)):
if ls[i]%2 == 0:
i=i+1
else:
return False

return True;
class Test(unittest.TestCase):
def test_even_numbers(self):
ls=[2,4,6,8,12]
print( even_numbers(ls))
self.assertEqual(True, even_numbers(ls))

unittest.main()

46​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

Output:

True
.
----------------------------------------------------------------------
Ran 1 test in 0.058s

OK

b. Write a test-case to check the function reverse_string which returns the reversed
string.

import unittest
def reverse(s):
return s[::-1]
class Test(unittest.TestCase):
def test_reverse(self):
s="mahesh"
print( reverse(s))
self.assertEqual("hseham", reverse(s))

unittest.main()

Output:

hseham
.
----------------------------------------------------------------------
Ran 1 test in 0.032s

OK

16.
a. ​Build any one classical data structure.

class Stack:
# initialize an empty list (stack)
def __init__(self):
self.mStack = []

47​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

# function to check if the stack is empty


def isEmpty(self):
return self.mStack == []

# function to push (insert) item into the stack


def push(self, item):
self.mStack.append(item)
print( "Inserted item: {}".format(item))

# function to pop (remove) item out of the stack


def pop(self):
if self.isEmpty() == False:
item = self.mStack.pop()
print( "Removed item : {}".format(item))
else:
print ("No item in stack")

# function to view the items in the stack


def view(self):
if self.isEmpty() == False:
for item in self.mStack:
print( item)
else:
print ("No item in stack")

# function to get the length of stack


def size(self):
return len(self.mStack)

# function to get the top item in stack


def top(self):
if self.isEmpty() == False:
return self.mStack[len(self.mStack)-1]
else:
return "No item in stack"

if __name__ == "__main__":
# create an instance of the stack class
mStack = Stack()

print ("---------------------------------")
print( "Implementation of Stack in Python")
print ("---------------------------------")

print ("Menu items")


print ("1. View the stack")
print ("2. Push item into stack")
print ("3. Pop item out of stack")
print ("4. Get the size of stack")
print ("5. Get the top item in stack")

48​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

print ("6. Quit the program")

while True:
user_input = int(input("Enter the option: "))

if user_input == 1:
mStack.view()
elif user_input == 2:
item = (input("Enter the item to be inserted: "))
mStack.push(item)
elif user_input == 3:
mStack.pop()
elif user_input == 4:
print (mStack.size())
elif user_input == 5:
print (mStack.top())
elif user_input == 6:
break

Output:

---------------------------------
Implementation of Stack in Python
---------------------------------
Menu items
1. View the stack
2. Push item into stack
3. Pop item out of stack
4. Get the size of stack
5. Get the top item in stack
6. Quit the program
Enter the option: 1
No item in stack
Enter the option: 2
Enter the item to be inserted: 10
Inserted item: 10
Enter the option: 2
Enter the item to be inserted: 20
Inserted item: 20
Enter the option: 2
Enter the item to be inserted: 30
Inserted item: 30
Enter the option: 1
10
20

49​ | ​Page
2​nd ​Year- 1​st ​Semester Python Programming Lab ​| ​2017-18

30
Enter the option: 4
3
Enter the option: 5
30
Enter the option: 3
Removed item : 30
Enter the option: 1
10
20
Enter the option:6

b. Write a program to solve knapsack problem.

def knapSack(W, wt, val, n):


K = [[0 for x in range(W+1)] for x in range(n+1)]
for i in range(n+1):
for w in range(W+1):
if i==0 or w==0:
K[i][w] = 0
elif wt[i-1] <= w:
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]],
K[i-1][w])
else:
K[i][w] = K[i-1][w]

return K[n][W]
val = [5, 3, 4]
wt = [3, 2, 1]
W = 5
n = len(val)
print(knapSack(W, wt, val, n))

Output:

50​ | ​Page
II-I Semester (R16) Data struct
cture through C++ Lab (2017-18)

KALLAM HAR
RANADHAREDDY INSTITUTE OF TEC
CHNOLOGY

Departmeent of Computer Science and Enginee


eering
2nd Year 1st Semester

Data structure
s through C++ Lab (2017-18)
8)

R16

Lab Manual

1
II-I Semester (R16) Data structure through C++ Lab (2017-18)

S.NO Title Date Page_NO


1 Write a C++ program for addition of two polynomial 19-06-2017 3
expressions?

2 Implementation of Multistack in a Single Array? 29-06-2017 5

3 Write a program to implement the operations on 03-07-2017 9


Circular Queue?

4 Write a program to implement Single linked list? 03-07-2017 13

5 Write a program to perform Binary Search Operation 10-07-2017 18


using divide and conques concept?

6 Implementation of Doubly linked list? 17-07-2017 20

7 Implementation of Binary Search trees. 24-07-2017 25

8 Implementation of Hash table. 31-07-2017 32

9 Implementation of Breadth First Search Techniques. 21-08-2017 34

10 Implementation of Breadth First Search Techniques. 28-08-2017 36

11 Write a program to Implement Prim’s Algorithm? 04-09-2017 38

12 Write a program to implement Kruskal’s Algorithm? 04-09-2017 39

13 Write a program to implement Dijkstra’s Algorithm? 11-09-2017 41

14 Write a program to implement Merge Sort? 11-09-2017 42

15 Write a program to implement Quick Sort? 18-09-2017 43

2
II-I Semester (R16) Data structure through C++ Lab (2017-18)

1. Write a C++ program for addition of two polynomial expressions?

#include<iostream.h>
#include<conio.h>
class poly
{
struct
{ int coef;
int expo;
} term[20];
int degree;

public:
void input()
{ int i;
cout<<"Enter number of terms";
cin>>degree;
cout<<"Enter coefficients and exponents for " << degree <<"
terms"<<endl;
for(i=0;i<degree;i++)
cin>>term[i].coef>>term[i].expo;

}
void add(poly A, poly B)
{
int i,j,k,l;
degree=A.degree+B.degree;
i=0;j=0;k=0;

while(i<A.degree && j<B.degree)


{
if( A.term[i].expo<B.term[j].expo)
{ term[k].coef=B.term[j].coef;
term[k].expo=B.term[j].expo;
j++;
k++;
}
if( A.term[i].expo>B.term[j].expo)
{ term[k].coef=A.term[i].coef;
term[k].expo=A.term[i].expo;
i++;
k++;
}
if( A.term[i].expo==B.term[j].expo)
{ term[k].coef=A.term[i].coef+B.term[j].coef;
term[k].expo=A.term[i].expo;
i++;
j++;
k++;
}
}
if(i<A.degree)
{ for(l=i; l<A.degree; l++)
{ term[k].coef=A.term[l].coef;

3
II-I Semester (R16) Data structure through C++ Lab (2017-18)

term[k].expo=A.term[l].expo;
k++;
}
}
if(j<B.degree)
{ for(l=j; l<B.degree; l++)
{ term[k].coef=B.term[l].coef;
term[k].expo=B.term[l].expo;
k++;
}
}
degree=k;
}

void display()
{ int i;
cout<<"polynomial is"<<endl;
for(i=0;i<degree;i++)
cout<<term[i].coef<<"x"<<term[i].expo<<" ";
}
};

main()
{
poly A,B,C;
cout<<"Enter Polynomial A:"<<endl;
A.input();
cout<<"Enter Polynomial B:"<<endl;
B.input();
C.add(A,B);
C.display();
getch();
}

Output:
Enter Polynomial A:
Enter number of terms 3
Enter coefficients and exponents for 3 terms
3 2 4 1 6 0
Enter Polynomial B:
Enter number of terms 3
Enter coefficients and exponents for 3 terms
5 2 5 1 8 0
Polynomial is
8x2 9x1 14x0

4
II-I Semester (R16) Data structure through C++ Lab (2017-18)

2. Implementation of Multistack in a Single Array?

#include <iostream.h>
#define max 10

class multistack
{
int top1, top2, stk_arr[max];
public:
multistack()
{
top1=-1;
top2=max;
}
void push()
{
int x,ch;
if(top1==top2-1)
{
cout<<"stack overflow "<<endl;
return;
}
cout<<"enter a no \n";
cin>>x;
cout<<"\n press 1 to push in stack1 or press 2 for stack2:";
cin>>ch;
if(ch==1)
stk_arr[++top1]=x;
else
stk_arr[--top2]=x;
cout<< x <<" element is successfully pushed \n";
return;
}

void pop()
{
int y,ch;
cout<<"\n press 1 to pop from stack1 or press 2 for stack2";
cin>>ch;
if(ch==1)
{
if(top1==-1)
{
cout<<"stack underflow\n";
return;
}
y=stk_arr[top1];
stk_arr[top1--]=0;
}
else
{
if(top2==max)
{
cout<<"stack underflow\n";

5
II-I Semester (R16) Data structure through C++ Lab (2017-18)

return;
}
y=stk_arr[top2];
stk_arr[top2++]=0;
}
cout<<y<< "\n element is successfully poped from stack \n";
return;
}

void display()
{
int i;
if (top1 == -1)
{
cout<<"stack 1 is empty \n";
}
else
{
cout<<"elements of Stack 1 are : \n";
for (i = 0; i <= top1; i++)
{
cout<<stk_arr[i]<<endl;
}
}
if (top2 == max)
{
cout<<"stack 2 is empty \n";
}
else
{
cout<<"elements of Stack 2 are : \n";
for (i = max-1; i >= top2; i--)
{
cout<<stk_arr[i]<<endl;
}
}
return ;
}

};
main()
{
multistack s;
int ch;
do
{
cout<<"\n 1:push\n 2:pop\n 3:display\n 4:exit\n choice:";
cin>>ch;
switch (ch)
{
case 1:s.push();
break;
case 2:s.pop();

6
II-I Semester (R16) Data structure through C++ Lab (2017-18)

break;
case 3:s.display();
break;
case 4:cout<<"exiting from program\n";
break;
default:cout<<"wrong choice\n";
break;
}
}while(ch!=4);

Output:
1:Push
2:Pop
3:Display
4:Exit
Choice: 1
Enter a no 10
Press 1 to push in stack 1 or press 2 for stack 2 : 1
10 element is successfully pushed
1:Push
2:Pop
3:Display
4:Exit
Choice: 1
Enter a no 20
Press 1 to push in stack 1 or press 2 for stack 2 : 1
20 element is successfully pushed
1:Push
2:Pop
3:Display
4:Exit
Choice: 1
Enter a no 100
Press 1 to push in stack 1 or press 2 for stack 2 : 2
100 element is successfully pushed
1:Push
2:Pop
3:Display
4:Exit
Choice: 3
Elements of stack 1 are:

7
II-I Semester (R16) Data structure through C++ Lab (2017-18)

20
10
Elements of stack 2 are:
200
100
1:Push
2:Pop
3:Display
4:Exit
Choice: 2
Press 1 to pop from stack 1 or press 2 for stack 2: 1
20
Element is successfully poped from stack
1:Push
2:Pop
3:Display
4:Exit
Choice: 2
Press 1 to pop from stack 1 or press 2 for stack 2: 2
200
Element is successfully poped from stack
1:Push
2:Pop
3:Display
4:Exit
Choice: 3
Elements of stack 1 are:
10
Elements of stack 2 are:
100

8
II-I Semester (R16) Data structure through C++ Lab (2017-18)

3. Write a program to implement the operations on Circular Queue?

#include <iostream.h>
#define max 5

class cqueue
{
int front,rear, cq[max];

public:

cqueue()
{
front= -1;
rear = -1;
}

void insert()
{
int x;
if(front==(rear+1)%max )
{
cout<<"Circular queue overflow "<<endl;
return;
}
cout<<"enter a no \n";
cin>>x;
rear=(rear+1)%max;
cq[rear]=x;
if(front==-1) front=0;
}

void del()
{
int y;
if(front==rear && rear==-1)
{
cout<<"circular queue underflow\n";
return;
}

y=cq[front];
cq[front]=0;
if(front==rear)
front=rear=-1;
else
front=(front+1)%max;
}

void display()
{
int i;
if (front==rear && rear==-1)
{

9
II-I Semester (R16) Data structure through C++ Lab (2017-18)

cout<<"circular is empty \n";


return;
}
cout<<"elements of circular queue are : \n";
if(front<=rear)
for (i = front; i <= rear; i++)
cout<<cq[i]<<endl;
else
{for (i = front; i <= max-1; i++)
cout<<cq[i]<<endl;
for (i = 0; i <= rear; i++)
cout<<cq[i]<<endl;
}
}
};

main()
{
cqueue q;
int ch;
do
{
cout<<"\n 1:insert\n 2:del\n 3:display\n 4:exit\n choice:";
cin>>ch;
switch (ch)
{
case 1:q.insert();
break;
case 2:q.del();
break;
case 3:q.display();
break;
case 4:cout<<"exiting from program\n";
break;
default:cout<<"wrong choice\n";
break;
}
}while(ch!=4);
}

Output:
1:insert
2:del
3:display
4:exit
Choice :1
Enter a no 10
1:insert
2:del
3:display

10
II-I Semester (R16) Data structure through C++ Lab (2017-18)

4:exit
Choice : 1
Enter a no 20
1:insert
2:del
3:display
4:exit
Choice : 1
Enter a no 30
1:insert
2:del
3:display
4:exit
Choice : 1
Enter a no 40
1:insert
2:del
3:display
4:exit
Choice : 1
Enter a no 50
1:insert
2:del
3:display
4:exit
Choice : 3
Elements of circular queue are:
10
20
30
40
50
1:insert
2:del
3:display
4:exit
Choice : 1
Circular queue overflow
1:insert
2:del
3:display
4:exit

11
II-I Semester (R16) Data structure through C++ Lab (2017-18)

Choice : 2
1:insert
2:del
3:display
4:exit
Choice : 2
1:insert
2:del
3:display
4:exit
Choice : 2
1:insert
2:del
3:display
4:exit
Choice : 3
Elements of circular queue are: 40
50
1:insert
2:del
3:display
4:exit
Choice : 2
1:insert
2:del
3:display
4:exit
Choice :2
Circular queue underflow
1:insert
2:del
3:display
4:exit
Choice :4

12
II-I Semester (R16) Data structure through C++ Lab (2017-18)

4. Write a program to implement Single linked list?

#include<iostream.h>
class Node
{
public:
int data;
Node* next;
};

class List:public Node


{

Node *start;
public:
List()
{
start=NULL;
}

void create()
{int num;
Node *temp=new Node;
if(start==NULL)
{
cout<<"\nEnter an Element:";
cin>>num;
temp->data=num;
temp->next=NULL;
start=temp;
}
else
{
cout<<"single linked list has an Elements, can not create new
list";
}
}

void insert()
{
Node *prev,*last;
int count,pos,ch,num;
Node *temp=new Node;
cout<<"\nEnter an Element:";
cin>>num;
temp->data=num;
temp->next=NULL;
cout<<"\nINSERT AS\n1:startNODE\n2:LASTNODE\n3:At specific
Node";
cout<<"\nEnter Your Choice:";
cin>>ch;
switch(ch)
{
case 1:

13
II-I Semester (R16) Data structure through C++ Lab (2017-18)

temp->next=start;
start=temp;
break;
case 2:
last=start;
while(last->next!=NULL)
last=last->next;
last->next=temp;
break;
case 3:
Node *p,*n;
cout<<"\nEnter the Position to Insert:";
cin>>pos;
n=start;
while(count!=pos)
{
p=n;
n=n->next;
count++;
}
if(count==pos)
{
p->next=temp;
temp->next=n;
}
else
cout<<"\nNot Able to Insert";
break;

}
}

void del()
{
Node *prev,*last=start;
int count=1,pos,ch;
cout<<"\nDELETE\n1:startNODE\n2:LASTNODE\n3:At specific Node";
cout<<"\nEnter Your Choice:";
cin>>ch;
switch(ch)
{
case 1:
if(start!=NULL)
{
cout<<"\nDeleted Element is "<<start->data;
start=start->next;
}
else
cout<<"\nNot Able to Delete";
break;
case 2:

while(last->next!=NULL)
{

14
II-I Semester (R16) Data structure through C++ Lab (2017-18)

prev=last;
last=last->next;
}
cout<<"\nDeleted Element is: "<<last->data;
prev->next=NULL;
break;
case 3:
Node *p,*n;
cout<<"\nEnter the Position to Insert:";
cin>>pos;
n=start;
while(count!=pos)
{
p=n;
n=n->next;
count++;
}
if(count==pos)
{
cout<<"\nDeleted Element is: "<<n->data;
p->next=n->next;
}
else
cout<<"\nNot Able to Delete";
break;
}
}
void display()
{
Node *last=start;
if(last==NULL)
{
cout<<"\nList is Empty";
}
while(last!=NULL)
{
cout<<last->data;
cout<<"-->";
last=last->next;
}
cout<<"NULL";
}

};

int main()
{
List l;
int ch;
while(1)
{
cout<<"\n**** MENU ****";
cout<<"\n1:CREATE FRIST NODE

15
II-I Semester (R16) Data structure through C++ Lab (2017-18)

\n2:INSERT\n3:DELETE\n4:DISPLAY\n5:EXIT\n";
cout<<"\nEnter Your Choice:";
cin>>ch;
switch(ch)
{
case 1:
l.create();
break;
case 2:
l.insert();
break;
case 3:
l.del();
break;
case 4:
l.display();
break;
case 5:
return 0;
}
}
return 0;
}

Output:
*** MENU ***
1:CREATE FRIST NODE
2:INSERT
3:DELETE
4:DISPLAY
5:EXIT
Enter your choice 1
Enter an element 10
*** MENU ***
1:CREATE FRIST NODE
2:INSERT
3:DELETE
4:DISPLAY
5:EXIT
Enter your choice 2
Enter an element 20
Insert as
1:startNODE
2:LASTNODE
3:At specific Node
Enter your choice 1

16
II-I Semester (R16) Data structure through C++ Lab (2017-18)

*** MENU ***


1:CREATE FRIST NODE
2:INSERT
3:DELETE
4:DISPLAY
5:EXIT
Enter your choice 2
Enter an element 30
Insert as
1:startNODE
2:LASTNODE
3:At specific Node
Enter your choice 3
Enter the position to insert 3
*** MENU ***
1:CREATE FRIST NODE
2:INSERT
3:DELETE
4:DISPLAY
5:EXIT
Enter your choice 4
20 10 30 NULL
*** MENU ***
1:CREATE FRIST NODE
2:INSERT
3:DELETE
4:DISPLAY
5:EXIT
Enter your choice 2
Enter an element 40
Insert as
1:start node
2:last node
3:at specific node
Enter your choice 2
*** MENU ***
1:CREATE FRIST NODE
2:INSERT
3:DELETE
4:DISPLAY
5:EXIT
Enter your choice 3

17
II-I Semester (R16) Data structure through C++ Lab (2017-18)

Delete
1:start node
2:last node
3:at specific node
Enter your choice 3
Enter the position to insert 2
Deleted element is 10
*** MENU ***
1:CREATE FRIST NODE
2:INSERT
3:DELETE
4:DISPLAY
5:EXIT
Enter your choice 4
20 30 40 NULL
*** MENU ***
1:CREATE FRIST NODE
2:INSERT
3:DELETE
4:DISPLAY
5:EXIT
Enter your choice 5

5. Write a program to perform Binary Search Operation using divide and conques concept?

#include<iostream.h>
#include<conio.h>
void main()
{
int a[50],i,key,n,result;
int low,mid,high;
void binarysearch(int a[],int key,int low,int high);
clrscr();
cout<<"how many numbers you want to enter?";
cin>>n;
cout<<"\n enter "<<n<<"elements in ascending order\n";
for(i=0;i<n;i++)
cin>>a[i];
cout<<"\n enter the elements to be searched";

18
II-I Semester (R16) Data structure through C++ Lab (2017-18)

cin>>key;
low=0;
high=n-1;
binarysearch(a,key,low,high);
getch();
}
void binarysearch(int a[],int key,int low,int high)
{
int mid;
if(low>high)
{ cout<<"Search element not found";
return;
}
else
{
mid=(low+high)/2;
if(key==a[mid])
{
cout<<"key elements is found at posion"<<mid+1;
return ;
}
if(key<a[mid])
{
high=mid-1;
binarysearch(a,key,low,high);
}
if(key>a[mid])
{
low=mid+1;
binarysearch(a,key,low,high);
}
}
}

Output:

How many numbers you want to enter? Enter 5 numbers in ascending order
10
20
30
40
50
Enter the element to be searched 10 key element is found position.

19
II-I Semester (R16) Data structure through C++ Lab (2017-18)

6. Implementation of Doubly linked list?

#include<iostream.h>
class Node
{
Public:
Node *prev;
int data;
Node *next;
};
class list:public Node
{
Node *start;
Node *last;
public:
List()
{
Start=NULL;
Last=NULL;

}
void create()
{
int num;
Node *temp=new Node;
if(start==NULL)
{
cout<<"\n Enter an element:";
cin>>num;
temp-->prev=NULL;
temp-->data-num;
temp-->next=NULL;
start=temp;
last=temp
}
else
{
cout<<"Double linked list has an element, cannot
create new list"
}
}
void insert()
{
int ch,num;
Node *temp=new Node;
cout<<"\n Enter an element";
cin>>num;
temp-->prev=NULL;
temp-->data-num;
temp-->next=NULL;
cout<<"\n INSERT AS \n 1:Start Node \n 2:" Last Node";
cout<<"\n Enter your choice:";

20
II-I Semester (R16) Data structure through C++ Lab (2017-18)

cin>>ch;
switch(ch)
{
case 1:
temp-->next=start;
start-->prev=temp;
start=temp;
break;
case 2:
last-->next=temp;
temp-->prev=last;
last=temp;

}
void del()
{
Node *p;
int ch;
cout<<"\n Delete \n 1:Start Node \n 2:Last Node";
cout<<"\n Enter your choice:";
cin>>ch;
switch(ch)
{
case 1:
if(start!=NULL)
{
cout<<"\n deleted element is:"<<start--
>data;
start=start-->next;
start-->prev=NULL;
}
else
{
cout<<"\n not able to delete";
break;
}
case 2:
cout<<"\n deleted element is:"<<last-->data;
last=last-->prev;
last-->next=NULL;
break;

}
}
void display()
{
Node *p;
int ch;
cout<<"\n Display\n 1:last to right \n 2:right to left";
cout<<"\n Enter your choice:";
cin>>ch;
switch(ch)

21
II-I Semester (R16) Data structure through C++ Lab (2017-18)

{
case 1:
p=start;
if(p==NULL)
{
cout<<"\n list is empty";
return;
}
cout<<"\n elements from left to right are
\n";
while(p!=NULL)
{
cout<<p-->data;
cout<<"-->";
p=p-->next;
}
break;
case 2:
p=last;
if(p==NULL)
{
cout<<"\n list is empty";
return;
}
cout<<"\n elements from right to left are
\n";
while(p!=NULL)
{
cout<<p-->data;
cout<<"-->";
p=p-->prev;
}
break;
}
}
};
main()
{
list d;
int ch;
do
{
cout<<"\n ***DOUBLE LINKED LIST MENU*** \n 1:create first
node \n 2:Insert \n 3:Delete \n 4: Display \n 5:Exit \n";
cout<<"\n Enter your choice:";
cin>>ch;
switch(ch)
{
case 1:
d.create();
break;
case 2:
d.insert();
break;

22
II-I Semester (R16) Data structure through C++ Lab (2017-18)

case 3:
d.del();
break;
case 4:
d.display();
break;
case 5:
break;

}
}while(ch<=4);
}

Output:
***DOUBLE LINKED LIST MENU***
1:create first node
2:Insert
3:Delete
4: Display
5:Exit
Enter your choice:1
Enter an element 10
***DOUBLE LINKED LIST MENU***
1:create first node
2:Insert
3:Delete
4: Display
5:Exit
Enter your choice:1
Double Linked List has an element, cannot create new list
***DOUBLE LINKED LIST MENU***
1:create first node
2:Insert
3:Delete
4: Display
5:Exit
Enter your choice:2
Enter an element 20
Insert as
1: Start Node
2: Last Node
Enter your choice:1

23
II-I Semester (R16) Data structure through C++ Lab (2017-18)

***DOUBLE LINKED LIST MENU***


1:create first node
2:Insert
3:Delete
4: Display
5:Exit
Enter your choice:2
Enter an element 30
Insert as
1: Start Node
2: Last Node
Enter your choice:2
***DOUBLE LINKED LIST MENU***
1:create first node
2:Insert
3:Delete
4: Display
5:Exit
Enter your choice:4
Display
1:left to right
2:right to left
Enter your choice:1
Elements from left to right are
20 10 30
***DOUBLE LINKED LIST MENU***
1:create first node
2:Insert
3:Delete
4: Display
5:Exit
Enter your choice:3
Delete
1:start node
2:last node
Enter your choice:2
Deleted element is 30
***DOUBLE LINKED LIST MENU***
1:create first node
2:Insert
3:Delete
4: Display

24
II-I Semester (R16) Data structure through C++ Lab (2017-18)

5:Exit
Enter your choice:4
Display
1:left to right
2:right to left
Enter your choice:2
Elements from right to left are
10 20 
***DOUBLE LINKED LIST MENU***
1:create first node
2:Insert
3:Delete
4: Display
5:Exit
Enter your choice:5

7. Implementation of Binary Search trees.

/* Binary Search Tree */


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

class node
{ public:

int data;
node *left;
node *right;
};

class BST:public node

{ public:
node *root;
BST()
{
root=NULL;
}

void create()
{int num;
node *temp=new node;
if(root==NULL)

25
II-I Semester (R16) Data structure through C++ Lab (2017-18)

{
cout<<"\nEnter an Element:";
cin>>num;
temp->left=NULL;
temp->data=num;
temp->right=NULL;
root=temp;
}
else
cout<<"BST has already a Root node";

}
void insert(node *t, int x)
{

node *temp=new node;


if(t->data == x)
{cout<<"duplicate data";
return;
}
if( x < t->data )
{
if( t->left == NULL )
{
temp->left=NULL;
temp->data=x;
temp->right=NULL;
t->left=temp;
return;
}
else
insert(t->left, x);

}
if( x > t->data )
{
if( t->right == NULL )
{
temp->left=NULL;
temp->data=x;
temp->right=NULL;
t->right=temp;
return;
}
else
insert(t->right, x);

void search(node *t,int x)


{
if(t==NULL)

26
II-I Semester (R16) Data structure through C++ Lab (2017-18)

{cout<<"element not found";


return;
}
if(t->data==x)
{
cout<<"Element found in the BST";
return;
}
if(x < t->data)
search(t->left,x);
if(x > t->data)
search(t->right,x);

void inorder(node *t)


{
if(t==NULL)
return;
if(t !=NULL)
{
inorder(t->left);
cout<<t->data<<" ";
inorder(t->right);
}
}
void preorder(node *t)
{
if(t !=NULL)
{
cout<<t->data<<" ";
preorder(t->left);
preorder(t->right);
}
}

void postorder(node *t)


{
if(t !=NULL)
{
postorder(t->left);
postorder(t->right);
cout<<t->data <<" ";
}
}
};

void main()
{
int ch,x;
BST b;
do
{

27
II-I Semester (R16) Data structure through C++ Lab (2017-18)

cout<<"\n**** BST MENU ****";


cout<<"\n1:CREATE ROOT NODE \n2:INSERT\n3:SEARCH\n4:INORDER
\n5:PREORDER\n6:POSTORDER\n7:EXIT\n";
cout<<"\nEnter Your Choice:";
cin>>ch;
switch(ch)
{
case 1:
b.create();
break;
case 2:
cout<<"Enter a Number: ";
cin>>x;
b.insert(b.root,x);
break;
case 3:
cout<<"Enter a Number to search: ";
cin>>x;
b.search(b.root,x);
break;

case 4:
b.inorder(b.root);
break;
case 5:
b.preorder(b.root);
break;
case 6:
b.postorder(b.root);
break;
case 7:
break;
}
}while(ch<=6);
getch();
}

Output:
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:1
Enter an element 50
**** BST MENU ****

28
II-I Semester (R16) Data structure through C++ Lab (2017-18)

1:CREATE ROOT NODE


2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:2
Enter an element 30
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:2
Enter an element 40
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:2
Enter an element 20
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:2
Enter an element 80
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT

29
II-I Semester (R16) Data structure through C++ Lab (2017-18)

3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:2
Enter an element 90
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:2
Enter an element 70
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:4
20 30 40 50 70 80 90
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:5
50 30 20 40 80 70 90
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER

30
II-I Semester (R16) Data structure through C++ Lab (2017-18)

5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:6
20 40 30 70 90 80 50
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:3
Enter an element 80
Element found in the BST
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:1
BST has already root node
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:7

31
II-I Semester (R16) Data structure through C++ Lab (2017-18)

8. Implementation of Hash table.

#include <iostream.h>
#include <conio.h>
#define SIZE 7

class node
{public:
int data;
node *next;
} ;

class hashtable : public node


{
public:
node *htable[SIZE];
hashtable()
{
int i ;
node *t;
for(i = 0; i < SIZE; i++)
{ t=new node;
t->data = NULL;
t->next = NULL;
htable[i]=t;
}
}

void insert(int n)
{
int index ;
index=hash(n);
if( htable[index]->data != NULL )
{
resolve(htable[index],index, n);
}
else
{
htable[index]->data=n;
}
}

int hash(int n)
{
return(n%SIZE);
}

void resolve(node *t, int loc, int n)


{
node *tmp,*p;

32
II-I Semester (R16) Data structure through C++ Lab (2017-18)

p=t;
while(p->next != NULL)
p = p->next;

tmp = new node;


tmp->data = n;
tmp->next = NULL;
p->next=tmp;

void display()
{
int i = 0;
node *target;
for(i = 0; i < SIZE; i++)
{
if(htable[i]->data != NULL)
{
target = htable[i];
while(target)
{
cout<<"\nlocation: "<< i <<" data:" << target->data;
target = target->next;
}
}
}
}

};

int main(void)
{
int n,i;
hashtable h;
clrscr();
cout<<"\nEnter any 5 integer numbers\n";
for(i=0;i<=4;i++)
{ cin>>n;
h.insert(n);
}

h.display();
getch();
}

Output:
Enter any 5 integer numbers
10

33
II-I Semester (R16) Data structure through C++ Lab (2017-18)

20
21
36
49
Location:0 data :21
Location:0 data :49
Location :1 data :36
Location :3 data :10
Location :6 data :20

9. Implementation of Depth First Search Techniques.

#include <iostream.h>
#include <conio.h>
int stack[10],top=-1;
void push(int item)
{

top=top+1;
stack[top]=item;

int pop()
{
int item;
if (top != -1)
{ item=stack[top];
top=top-1;
return(item);
}
}

void DFT(int graph[][10],int n,int start)


{ int v[10]={0,0,0,0,0,0,0,0,0,0};
int i,j,x;
push(start);
v[start]=1;
cout<<"\n";
while(1)
{
start=pop();
cout<<start+1 <<" ";
x=start;
for(i=0;i<n;i++)
{
if(graph[x][i]==1 && v[i]!=1)

34
II-I Semester (R16) Data structure through C++ Lab (2017-18)

{
push(i);
v[i]=1;

}
}
if(top==-1)
break;
}

void main()
{
int graph[10][10];
int i,j,n,v1,v2;
char ch,type;

clrscr();

cout<<"Enter number of Verteces:";


cin>>n;

for(i=0;i<n;i++)
{ for(j=0;j<n;j++)
graph[i][j]=0 ;
}
do
{
cout<<"Enter the Edge of graph";
cin>>v1>>v2;
graph[v1-1][v2-1]=1;
graph[v2-1][v1-1]=1;
cout<<"Another edge y/n?";
cin>>ch;
}
while(ch=='y');
cout<<"The Depth First Traversal of graph is\n";
DFT(graph,n,0);
getch();
}

Output:
Enter numbers of vertices 5
Enter the edge of graph 0 1
Another edge y/n? y
Enter the edge of the graph 02
Another edge y/n? y
Enter the edge of graph 03

35
II-I Semester (R16) Data structure through C++ Lab (2017-18)

Another edge y/n?y


Enter the edge of the graph 14
Another edge y/n?y
Enter the edge of the graph 23
Another edge y/n?y
Enter the edge of the graph 24
Another edge y/n?n
Enter the edge of the graph 34
Another edge y/n?n
The depth first traversal of graph is 0 3 4 2 1

10. Implementation of Breadth First Search Techniques.

#include <iostream.h>
#include <conio.h>
int queue[10],front=-1,rear=-1;

void insert(int n)
{
if(rear<=5)
{
rear++;
queue[rear]=n;
}
}
int isempty()
{
if (front==rear )
return 1;
else
return 0;
}

int del()
{ int n;
if(!isempty())
{
front++;
n=queue[front];
return n;
}
}

void BFT(int graph[][10],int n,int start)


{ int v[6]={0,0,0,0,0,0};
int i,j;

insert(start);

36
II-I Semester (R16) Data structure through C++ Lab (2017-18)

v[start]=1;
while(!isempty())
{ start=del();
cout<<start+1<<" ";
for(i=0;i<n;i++)
{
if(graph[start][i]==1 && v[i]==0)
{
insert(i);
v[i]=1;
}
}
}

void main()
{
int graph[10][10];
int i,j,n,v1,v2;
char ch,type;

clrscr();

cout<<"Enter number of Vertices:";


cin>>n;
for(i=0;i<n;i++)
{ for(j=0;j<n;j++)
graph[i][j]=0 ;
}

do
{
cout<<"Enter the Edge of graph";
cin>>v1>>v2;
graph[v1-1][v2-1]=1;
graph[v2-1][v1-1]=1;
cout<<"Another edge y/n?";
cin>>ch;
} while(ch=='y');

cout<<"Breadth First Search of Graph is \n ";


BFT(graph,n,0);

getch();

Output:
Enter numbers of vertices 5
Enter the edge of graph 0 1

37
II-I Semester (R16) Data structure through C++ Lab (2017-18)

Another edge y/n? y


Enter the edge of the graph 02
Another edge y/n? y
Enter the edge of graph 03
Another edge y/n?y
Enter the edge of the graph 14
Another edge y/n?y
Enter the edge of the graph 23
Another edge y/n?y
Enter the edge of the graph 24
Another edge y/n?n
Enter the edge of the graph 34
Another edge y/n?n
Breadth First Search of Graph is 0 1 2 3 4

11. Write a program to Implement Prim’s Algorithm?

#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,u,v,n,i,j,nedge=1;
int visited[10]={0},min,mincost=0,cost[10][10];

clrscr();
cout<<"\n Enter the number of Verteces:";
cin>>n;
cout<<"\n Enter the adjacency matrix:\n";
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
cin>>cost[i][j];
if(cost[i][j]==0)
cost[i][j]=999;
}
visited[1]=1;
cout<<"\n";
while(nedge<n)
{
min=999;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]<min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;

38
II-I Semester (R16) Data structure through C++ Lab (2017-18)

b=v=j;
}
if(visited[u]==0 || visited[v]==0)
{
cout<<"\n Edge "<<nedge << a << "-->" << b <<" cost:"<<min;
nedge++;
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
cout<<"\n Minimun cost="<<mincost;
getch();
}

Output:
Enter the no of vertices: 4
Enter the adjacency matrix :
0 6 4 3
6 0 2 5
4 2 0 7
3 5 7 0
Enter 11 4 cost:3
Enter 21 3 cost:4
Enter 33 2 cost:2
Minimum cost =9

12. Write a program to implement Kruskal’s Algorithm?

#include<iostream.h>
#include<conio.h>
int i,j,k,a,b,u,v,n,nedge=1;
int min,mincost=0,cost[9][9];
void main()
{
clrscr();
cout<<"\nEnter the no. of vertices\n";
cin>>n;
cout<<"\nEnter the cost adjacency matrix\n";
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cin>>cost[i][j];
if(cost[i][j]==0)
cost[i][j]=999;

39
II-I Semester (R16) Data structure through C++ Lab (2017-18)

}
}
cout<<"\nThe edges of Minimum Cost Spanning Tree are\n\n";
while(nedge<n)
{ min=999;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}

cout<<"("<<a<<"-->"<<b<< ") ="<<min<<"\n";


mincost +=min;
nedge++;

cost[a][b]=cost[b][a]=999;

}
cout<<"\n\tMinimum cost = "<<mincost;
getch();
}

Output:
Enter the no of vertices: 4
Enter the cost adjacency matrix :
0 6 4 3
6 0 2 5
4 2 0 7
3 5 7 0
The edges of minimum cost spanning tree are
(2 3)=2
(1 4)=3
(1 3)=4
Minimum cost=9

40
II-I Semester (R16) Data structure through C++ Lab (2017-18)

13. Write a program to implement Dijkstra’s Algorithm?

#include<iostream.h>
#include<conio.h>
void dij(int n,int v,int cost[10][10],int dist[])
{
int i,j,u,count,flag[10],min;
for(i=1;i<=n;i++)
{flag[i]=0;
dist[i]=cost[v][i];
}
count=2;
flag[1]=1;
while(count<n)
{
min=99;
for(j=1;j<=n;j++)
if(dist[j]<min && !flag[j])
{min=dist[j];
u=j;
}
flag[u]=1;
for(j=1;j<=n;j++)
if((dist[u]+cost[u][j]<dist[j]) && !flag[j])
dist[j]=dist[u]+cost[u][j];

count++;
}
}
void main()
{
int n,v,i,j,cost[10][10],dist[10];

clrscr();
cout<<"\n Enter the number of nodes:";
cin>>n;
cout<<"\n Enter the cost matrix:\n";
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
cin>>cost[i][j];
}
cout<<"\n Enter the source :";
cin>>v;
dij(n,v,cost,dist);
cout<<"\n Shortest path:\n";
for(i=1;i<=n;i++)
if(i!=v)
cout<<v <<"-> "<<i << "cost=" << dist[i] <<"\n";
getch();
}

41
II-I Semester (R16) Data structure through C++ Lab (2017-18)

Output:
Enter the no of vertices: 4
Enter the cost matrix:
0 6 4 3
6 0 2 5
4 2 0 7
3 5 7 0
Enter the source: 2
Shortest path:
2 1 cost =6
2 3 cost=2
2 4 cost=5

14. Write a program to implement Merge Sort?

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

void merge(int * , int , int , int );

void mergesort(int *array, int left, int right)


{
int mid = (left+right)/2;

if(left<right)
{
mergesort(array,left,mid);
mergesort(array,mid+1,right);
merge(array,left,mid,right);
}
}

void merge(int *array, int left, int mid, int right)


{

int tempArray[50];
int n,i;
int pos=0, lpos = left, rpos = mid + 1;
n=right-left+1;

while(lpos <= mid && rpos <= right)


{
if(array[lpos] < array[rpos])
tempArray[pos++] = array[lpos++];
else
tempArray[pos++] = array[rpos++];

42
II-I Semester (R16) Data structure through C++ Lab (2017-18)

while(lpos <= mid) tempArray[pos++] = array[lpos++];


while(rpos <= right)tempArray[pos++] = array[rpos++];

/* Copy back the sorted array to the original array */


for(i = 0;i < pos; i++)
array[i+left] = tempArray[i];
return;
}

void main()
{
int n;
int array[20];
int i;
cout<<"Enter No of Elements";
cin>>n;
cout<<"Enter Numbers " ;
for(i = 0;i < n;i++)
cin>>array[i];

/* Calling this functions sorts the array */


mergesort(array,0,n-1);
cout<<"\n Sorted Array is \n";
for(i = 0;i < n;i++)
cout<<array[i]<<" ";

getch();
}

Output:
Enter no of elements 5
Enter numbers 5 3
25
18
4
45
Sorted array is
4 18 25 45 53

15. Write a program to implement Quick Sort?

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

43
II-I Semester (R16) Data structure through C++ Lab (2017-18)

void quick(int a[],int first,int last)


{
int i,j,pivot,temp;
if(first<last)
{
pivot=a[first];
i=first;
j=last;
while(i<j)
{
while(a[i] <= pivot && i<j ) i++;
while(a[j]>pivot && i<=j ) j--;
if(i<=j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[j];
a[j]=a[first];
a[first]=temp;

quick(a,first,j-1);
quick(a,j+1,last); }
}

void main()
{
int a[50];
int n,i;
clrscr();
cout<<"\n enter n value";
cin>>n;
cout<<"\n Enter numbers ";
for(i=0;i<n;i++)
cin>>a[i];
quick(a,0,n-1);
cout<<"the sorted numbers are \n";
for(i=0;i<n;i++)
cout<<a[i] << " ";
getch();
}

Output:
Enter n value 5
Enter number 4 53 45 25 18
The sorted numbers are
4 18 25 45 53

44

Powered by TCPDF (www.tcpdf.org)

You might also like