Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
54 views

Python Lab Manual

The document discusses Python programming basics like running code interactively and in scripts, arithmetic operations, control flow structures like if/else, for and while loops. It also includes examples of finding distance between points, checking even/odd numbers, printing Fibonacci sequences and calculating sums.

Uploaded by

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

Python Lab Manual

The document discusses Python programming basics like running code interactively and in scripts, arithmetic operations, control flow structures like if/else, for and while loops. It also includes examples of finding distance between points, checking even/odd numbers, printing Fibonacci sequences and calculating sums.

Uploaded by

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

PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

S.NO DATE PROGRAM NAME PAGENO SIGN

Python programming
04
1. Basics

07
2. Operation

10
3. Control Flow

15
4. Data Structure

5. 18
Functions

23
6. Function-Problem Solving

7. 27
Multi-d-Lists

8. 32
OOPS
1. Robot
2. ATM machine
9. 37
Testing

10. 40
Advanced
1. classical data structure
2. Knapsack problem

1 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

S.NO DATE PROGRAM NAME PAGENO SIGN

Operating system
46
1. CPU Scheduling Algorithms
a. FCFS
b. SJF
c. Round Robin
d. Priority.

2. 53
Producer-Consumer Problem using
Semaphores

58
3. Dining Philosophers Problem
62
4. MVT and MFT
66
5. Memory Allocation Techniques
a. Worst fit
b. Best fit
c. First fit.
73
6. Page Replacement Algorithms
a. FIFO
b. LRU
c. OPTIMAL
80
7. File Organization Techniques
a. Single level directory
b. Two level directory
86
8. File Allocation Strategies
a. Sequential
b. Indexed
c. Linked
92
9. Deadlock Avoidance

95
10. Deadlock Prevention

Disk Scheduling Algorithms 101


11. a. FCFS
b. SCAN
c. C-SCAN

2 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Python programming

3 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:01
Basics

Aim:
a. Running instructions in Interactive interpreter and a Python Script
b. Write a program to purposefully raise Indentation Error and correct it

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.py
3. Run the program using the command Python3 filename.py
4. Save the program with extension .py.
5. Stop the program.

4 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
a)
>>> 3+5
8
>>> 4-2

2
>>> 8/2

4.0

b)
[To purposefully raise Indentation Error]
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:

5 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

[Correct code]
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:

RESULT:
Thus the program has been executed successfully and the output is verified.

6 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:02
Operations

Aim:
To write a program to compute distance between two points taking input from the user
(Pythagorean Theorem).

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.py
3. Python print() command takes in any number of parameters, and prints them out on
one line of text.
4. Run the program using the command Python3 filename.py
5. Save the program with extension .py.
6. Stop the program.

7 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
a)
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:

8 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

RESULT:
Thus the program has been executed successfully and the output is verified.

9 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:03
Control Flow

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

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

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

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

e. 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,...
f. By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.py
3. Python print() command takes in any number of parameters, and prints them out on
one line of text.
4. Run the program using the command Python3 filename.py
5. Save the program with extension .py.
6. Stop the program.

10 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

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

OUTPUT:

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

11 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

OUTPUT:

c)
str="i am python developer"
for i in str:
print(i)

OUTPUT:

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

12 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

OUTPUT:

e)
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:

13 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

f)
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:

RESULT:
Thus the program has been executed successfully and the output is verified.

14 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:04
data structure

Aim:
a. Write a program to count the numbers of characters in the string and store
them in adictionary data structure

b. Write a program to use split and join methods in the string and trace a
birthday witha dictionary data structure.

c. Write a program combine lists that combines these lists into a dictionary.

d. 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?

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.py
3. Python print() command takes in any number of parameters, and prints them out on
one line of text.
4. Run the program using the command Python3 filename.py
5. Save the program with extension .py.
6. Stop the program.

15 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

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

OUTPUT:

b)
a="hi i am python programmer"
b=a.split()
print (b)
c=" ".join(b)
print(c)

OUTPUT:

16 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

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

OUTPUT:

RESULT:
Thus the program has been executed successfully and the output is verified.

17 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:05
functions

Aim:
a) Write a function ball collides 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 tupelo of(x,y,r), r being the radius If(distance
between two balls centers) <= (sum of the irradii) then(they are colliding)

b) Find mean, median, mode for the given set of numbers in a list.

c) 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.

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

e) Write a function unique to find all the unique elements of a list.

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.py
3. Python print() command takes in any number of parameters, and prints them out on
one line of text.
4. Run the program using the command Python3 filename.py
5. Save the program with extension .py.
6. Stop the program.

18 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
a)
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)
c=ball_collide(100,200,20,200,100,10)
print(c)

Output:

19 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

b)
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:

c)
from difflib import SequenceMatcherdef
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")
else:
print("Both Strings are Different")

20 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Output:

d)
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:

21 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

e)
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')
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:

RESULT:
Thus the program has been executed successfully and the output is verified.

22 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:06

Functions - Problem Solving

Aim:
a) Write a function cumulative product to compute cumulative product of a list of numbers.

b) Write a function reverse to reverse a list without, using the reverse function.

c) Write function to compute GCD, LCM of two numbers. Each function shouldn’t exceed one
line.

Algorithm:
1) Start the Program
2) Type the codings in Text editor using the command gedit filename.py
3) Python print() command takes in any number of parameters, and prints them out
on one line of text.
4) Run the program using the command Python3 filename.py
5) Save the program with extension .py.
6) Stop the program.

23 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
a)
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:

24 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

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

Output:

c)
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)))

25 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Output:

RESULT:
Thus the program has been executed successfully and the output is verified.

26 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:07
Multi-D Lists

Aim:
a) Write a program that defines a matrix and prints

b) Write a program to perform addition of two square matrices

c) Write a program to perform multiplication of two square matrices

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.py
3. Python print() command takes in any number of parameters, and prints them out on
one line of text.
4. Run the program using the command Python3 filename.py
5. Save the program with extension .py.
6. Stop the program.

27 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
a)
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)

Output:

28 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

b)
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):
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:

29 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

c)
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)
print("1st Matrix X:",X)
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)
else:
print("Multiplication is not possible")

30 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Output:

RESULT:
Thus the program has been executed successfully and the output is verified.

31 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:08
OOPs

Aim:
a) Class variables and instance variable and illustration of these lf variable

i) Robot

ii) ATM Machine

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.py
3. Python print() command takes in any number of parameters, and prints them out on
one line of text.
4. Run the program using the command Python3 filename.py
5. Save the program with extension .py.
6. Stop the program.

32 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
a)
class Robot:
population=0
def init (self, name):
self.name = name
print('(Initializing {0})'.format(self.name))
Robot.population += 1def 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()
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 destroythem.")
del d
del d1
Robot.howMany()

33 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Output:

b)
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"))
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):

34 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

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)
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)

35 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

def Exit():
print ("Exit")
t1 = Bank('mahesh', 1453210145,5000)print (t1)

Output:

RESULT:
Thus the program has been executed successfully and the output is verified.

36 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:09
Testing

Aim:
a) Write a test-case to check the function even numbers which return True on passing a list of
all even numbers

b) Write a test- case to check the function reverse string which returns the reversed string

Algorithm:
1) Start the Program
2) Type the codings in Text editor using the command gedit filename.py
3) Python print() command takes in any number of parameters, and prints them out
on one line of text.
4) Run the program using the command Python3 filename.py
5) Save the program with extension .py.
6) Stop the program.

37 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
a)
import unittest
def even_numbers(ls):
i=0
for i in range(len(ls)):
if ls[i]%2 == 0:
i=i+1else:
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()

output:

b)
import unittestdef 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()

38 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

output:

RESULT:
Thus the program has been executed successfully and the output is verified.

39 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:10
advanced

Aim:
a) Build any one classical data structure.

b) Write a program to solve Knapsack problem.

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.py
3. Python print() command takes in any number of parameters, and prints them out on
one line of text.
4. Run the program using the command Python3 filename.py
5. Save the program with extension .py.
6. Stop the program.

40 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
a)
class Stack:
# initialize an empty list (stack)
def init (self):
self.mStack = [ ]
# 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 stackdef 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()

41 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

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")
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

42 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Output:

b)
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))

43 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

output:

RESULT:
Thus the program has been executed successfully and the output is verified.

44 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

OPERATING SYSTEM

45 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:01
Cpu scheduling algorithms

Aim:
Simulate the following CPU scheduling algorithms.

a) FCFS b) SJF c) Round Robin d) Priority.

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.c
3. Compile the program using the command cc filename.c -o x.out.
4. Run the program using the command ./x.out.
5. Save the program with extension .c.
6. Stop the program.

46 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
a)FCFS
#include<stdio.h>
int main()
{
int bt[20], wt[20], tat[20], i, n;
float wtavg, tatavg;
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
}
wt[0] = wtavg = 0;
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", i, bt[i], wt[i], tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n);
printf("\nAverage Turnaround Time -- %f", tatavg/n);
return(0);
}

47 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Output:

b)SJF
#include<stdio.h>
int main()
{
int p[20],bt[20],wt[20],tat[20],k,i,n,temp;
float wtavg,tatavg;
printf("\n Enter the number of process...");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i]=i;
printf("\n Enter burst time for proces%d......",i);
scanf("%d",&bt[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(bt[i]>bt[k])
{
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=p[i];
p[i]=p[k];
p[k]=temp;
}
wt[0]=wtavg=0;

48 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

tat[0]=tatavg=bt[0];
for(i=1;i<n;i++)
{
wt[i]=wt[i-1]+bt[i-1];
tat[i]=tat[i-1]+bt[i];
wtavg=wtavg+wt[i];
tatavg=tatavg+tat[i];
}
printf("\n\tPROCESS\tBURST TIME\t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\tp%d\t\t%d\t\t%d\t\t%d\t\t",p[i],bt[i],wt[i],tat[i]);
printf("\n Average waiting time.......%f",wtavg/n);
printf("\n Average turnaround time.......%f",tatavg/n);
}

OUTPUT:

49 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

c)Round Robin
#include<stdio.h>
int main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0,att=0,temp=0;
printf("Enter the no of processes -- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice -- ");
scanf("%d",&t);
max=bu[0];
for(i=1;i<n;i++)
if(max<bu[i])
max=bu[i];
for(j=0;j<(max/t)+1;j++)
for(i=0;i<n;i++)
if(bu[i]!=0)
if(bu[i]<=t) {
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else {
bu[i]=bu[i]-t;
temp=temp+t;
}
for(i=0;i<n;i++){
wa[i]=tat[i]-
ct[i]; att+=tat[i];
awt+=wa[i];}
printf("\nThe Average Turnaround time is -- %f",att/n);
printf("\nThe Average Waiting time is -- %f ",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
return(0);
}

50 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Output:

d) Priority
#include<stdio.h>
int main()
{
int p[20],bt[20],pri[20], wt[20],tat[20],i, k, n, temp; float wtavg,tatavg;
printf("Enter the number of processes --- ");
scanf("%d",&n);
for(i=0;i<n;i++){
p[i] = i;
printf("Enter the Burst Time & Priority of Process %d --- ",i); scanf("%d %d",&bt[i],
&pri[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(pri[i] > pri[k]){
temp=p[i];
p[i]=p[k];
p[k]=temp;
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=pri[i];
pri[i]=pri[k];
pri[k]=temp;
}

51 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

wtavg = wt[0] = 0;
tatavg = tat[0] = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] + bt[i-1];
tat[i] = tat[i-1] + bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\nPROCESS\t\tPRIORITY\tBURST TIME\tWAITING TIME\tTURNAROUND
TIME");
for(i=0;i<n;i++)
printf("\n%d \t\t %d \t\t %d \t\t %d \t\t %d ",p[i],pri[i],bt[i],wt[i],tat[i]);
printf("\nAverage Waiting Time is --- %f",wtavg/n); printf("\nAverage Turnaround Time is --
- %f",tatavg/n);
return(0);
}

OUTPUT:

RESULT:
Thus the program has been executed successfully and the output is verified.

52 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:02
producer-consumer problem
using Semaphores

Aim:
To write a C program to simulate producer-consumer problem using Semaphores.

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.c
3. Compile the program using the command cc filename.c -o x.out.
4. Run the program using the command ./x.out.
5. Save the program with extension .c.
6. Stop the program.

53 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
#include <stdio.h>
#include <stdlib.h>

// Initialize a mutex to 1
int mutex = 1;

// Number of full slots as 0


int full = 0;

// Number of empty slots as size


// of buffer
int empty = 10, x = 0;

// Function to produce an item and


// add it to the buffer
void producer()
{
// Decrease mutex value by 1
--mutex;

// Increase the number of full


// slots by 1
++full;

// Decrease the number of empty


// slots by 1
--empty;

// Item produced
x++;
printf("\nProducer produces"
"item %d",
x);

// Increase mutex value by 1


++mutex;
}

// Function to consume an item and


// remove it from buffer
void consumer()
{
// Decrease mutex value by 1
--mutex;

54 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

// Decrease the number of full


// slots by 1
--full;

// Increase the number of empty


// slots by 1
++empty;
printf("\nConsumer consumes "
"item %d",
x);
x--;

// Increase mutex value by 1


++mutex;
}

// Driver Code
int main()
{
int n, i;
printf("\n1. Press 1 for Producer"
"\n2. Press 2 for Consumer"
"\n3. Press 3 for Exit");

// Using '#pragma omp parallel for'


// can give wrong value due to
// synchronization issues.

// 'critical' specifies that code is


// executed by only one thread at a
// time i.e., only one thread enters
// the critical section at a given time
#pragma omp critical

for (i = 1; i > 0; i++) {

printf("\nEnter your choice:");


scanf("%d", &n);

// Switch Cases
switch (n) {
case 1:

// If mutex is 1 and empty


// is non-zero, then it is
// possible to produce
if ((mutex == 1)

55 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

&& (empty != 0)) {


producer();
}

// Otherwise, print buffer


// is full
else {
printf("Buffer is full!");
}
break;

case 2:

// If mutex is 1 and full


// is non-zero, then it is
// possible to consume
if ((mutex == 1)
&& (full != 0)) {
consumer();
}

// Otherwise, print Buffer


// is empty
else {
printf("Buffer is empty!");
}
break;

// Exit Condition
case 3:
exit(0);
break;
}
}
}

56 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

OUTPUT:

RESULT:
Thus the program has been executed successfully and the output is verified.

57 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:03
Dining-philosophers problem

Aim:
To write a C program to simulate the concept of Dining-philosophers problem.

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.c
3. Compile the program using the command cc filename.c -o x.out.
4. Run the program using the command ./x.out.
5. Save the program with extension .c.
6. Stop the program.

58 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
#include<stdio.h>

#define n 4

int compltedPhilo = 0,i;

struct fork{
int taken;
}ForkAvil[n];

struct philosp{
int left;
int right;
}Philostatus[n];

void goForDinner(int philID){ //same like threads concept here cases implemented
if(Philostatus[philID].left==10 && Philostatus[philID].right==10)
printf("Philosopher %d completed his dinner\n",philID+1);
//if already completed dinner
else if(Philostatus[philID].left==1 && Philostatus[philID].right==1){
//if just taken two forks
printf("Philosopher %d completed his dinner\n",philID+1);

Philostatus[philID].left = Philostatus[philID].right = 10; //remembering that he


completed dinner by assigning value 10
int otherFork = philID-1;

if(otherFork== -1)
otherFork=(n-1);

ForkAvil[philID].taken = ForkAvil[otherFork].taken = 0; //releasing forks


printf("Philosopher %d released fork %d and
fork %d\n",philID+1,philID+1,otherFork+1);
compltedPhilo++;
}
else if(Philostatus[philID].left==1 && Philostatus[philID].right==0){ //left already
taken, trying for right fork
if(philID==(n-1)){
if(ForkAvil[philID].taken==0){ //KEY POINT OF THIS PROBLEM, THAT
LAST PHILOSOPHER TRYING IN reverse DIRECTION
ForkAvil[philID].taken = Philostatus[philID].right = 1;
printf("Fork %d taken by philosopher %d\n",philID+1,philID+1);
}else{
printf("Philosopher %d is waiting for fork %d\n",philID+1,philID+1);
}

59 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

}else{ //except last philosopher case


int dupphilID = philID;
philID-=1;

if(philID== -1)
philID=(n-1);

if(ForkAvil[philID].taken == 0){
ForkAvil[philID].taken = Philostatus[dupphilID].right = 1;
printf("Fork %d taken by Philosopher %d\n",philID+1,dupphilID+1);
}else{
printf("Philosopher %d is waiting for Fork %d\n",dupphilID+1,philID+1);
}
}
}
else if(Philostatus[philID].left==0){ //nothing taken yet
if(philID==(n-1)){
if(ForkAvil[philID-1].taken==0){ //KEY POINT OF THIS PROBLEM, THAT
LAST PHILOSOPHER TRYING IN reverse DIRECTION
ForkAvil[philID-1].taken = Philostatus[philID].left = 1;
printf("Fork %d taken by philosopher %d\n",philID,philID+1);
}else{
printf("Philosopher %d is waiting for fork %d\n",philID+1,philID);
}
}else{ //except last philosopher case
if(ForkAvil[philID].taken == 0){
ForkAvil[philID].taken = Philostatus[philID].left = 1;
printf("Fork %d taken by Philosopher %d\n",philID+1,philID+1);
}else{
printf("Philosopher %d is waiting for Fork %d\n",philID+1,philID+1);
}
}
}else{}
}

int main(){
for(i=0;i<n;i++)
ForkAvil[i].taken=Philostatus[i].left=Philostatus[i].right=0;

while(compltedPhilo<n){
/* Observe here carefully, while loop will run until all philosophers complete dinner
Actually problem of deadlock occur only thy try to take at same time
This for loop will say that they are trying at same time. And remaining status will print by go
for dinner function
*/
for(i=0;i<n;i++)
goForDinner(i);

60 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

printf("\nTill now num of philosophers completed dinner are %d\n\n",compltedPhilo);


}

return 0;

Output:

RESULT:
Thus the program has been executed successfully and the output is verified.

61 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:04
MVT & Mft

Aim:
To write a C program to simulate the concept of MVT and MFT.

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.c
3. Compile the program using the command cc filename.c -o x.out.
4. Run the program using the command ./x.out.
5. Save the program with extension .c.
6. Stop the program.

62 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:

MVT:

#include<stdio.h>

int main()
{
int ms,mp[10],i, temp,n=0;
char ch = 'y';

printf("\nEnter the total memory available (in Bytes)-- ");


scanf("%d",&ms);
temp=ms;
for(i=0;ch=='y';i++,n++)
{
printf("\nEnter memory required for process %d (in Bytes) -- ",i+1);
scanf("%d",&mp[i]);
if(mp[i]<=temp)
{
printf("\nMemory is allocated for Process %d ",i+1);
temp = temp - mp[i];
}
else
{
printf("\nMemory is Full");
break;
}
printf("\nDo you want to continue(y/n) -- ");
scanf(" %c", &ch);
}
printf("\n\nTotal Memory Available -- %d", ms);
printf("\n\n\tPROCESS\t\t MEMORY ALLOCATED ");
for(i=0;i<n;i++)
printf("\n \t%d\t\t%d",i+1,mp[i]);
printf("\n\nTotal Memory Allocated is %d",ms-temp);
printf("\nTotal External Fragmentation is %d",temp);

return 0;
}

63 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Output:

MFT:

#include<stdio.h>
int main()
{
int ms, bs, nob, ef,n, mp[10],tif=0;
int i,p=0;

printf("Enter the total memory available (in Bytes) -- ");


scanf("%d",&ms);
printf("Enter the block size (in Bytes) -- ");
scanf("%d", &bs);
nob=ms/bs;
ef=ms - nob*bs;
printf("\nEnter the number of processes -- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter memory required for process %d (in Bytes)-- ",i+1);
scanf("%d",&mp[i]);
}

64 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

printf("\nNo. of Blocks available in memory -- %d",nob);


printf("\n\nPROCESS\tMEMORY REQUIRED\t ALLOCATED\tINTERNAL
FRAGMENTATION");
for(i=0;i<n && p<nob;i++)
{
printf("\n %d\t\t%d",i+1,mp[i]);
if(mp[i] > bs)
printf("\t\tNO\t\t---");
else
{
printf("\t\tYES\t%d",bs-mp[i]);
tif = tif + bs-mp[i];
p++;
}
}
if(i<n)
printf("\nMemory is Full, Remaining Processes cannot be accomodated");
printf("\n\nTotal Internal Fragmentation is %d",tif);
printf("\nTotal External Fragmentation is %d",ef);

return 0;
}

Output:

RESULT:
Thus the program has been executed successfully and the output is verified.

65 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:05
memory allocation Techniques

Aim:
Write a C program to simulate the following contiguous memory allocation Techniques.

a) Worst fit b) Best fit c) First fit.

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.c
3. Compile the program using the command cc filename.c -o x.out.
4. Run the program using the command ./x.out.
5. Save the program with extension .c.
6. Stop the program.

66 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
a) Worst Fit
#include<stdio.h>
#define max 25
int main()
{
int
frag[max],b[max],f[max],i,j,nb,nf,temp; static int bf[max],ff[max];
printf("\n\tMemory Management Scheme - First Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
{
ff[i]=j;
break;
}
}
}
frag[i]=temp;
bf[ff[i]]=1;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);

67 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

return(0);
}

Output:

b) Best Fit
#include<stdio.h>

void main()
{
int fragment[20],b[20],p[20],i,j,nb,np,temp,lowest=9999;
static int barray[20],parray[20];
printf("\n\t\t\t Memory allocation Techniques - Best Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of processes:");
scanf("%d",&np);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block no.%d:",i);
scanf("%d",&b[i]);
}
printf("\nEnter the size of the processes :-\n");
for(i=1;i<=np;i++)
{
printf("Process no.%d:",i);

68 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

scanf("%d",&p[i]);
}
for(i=1;i<=np;i++)
{
for(j=1;j<=nb;j++)
{
if(barray[j]!=1)
{
temp=b[j]-p[i];
if(temp>=0)
if(lowest>temp)
{
parray[i]=j;
lowest=temp;
}
}
}
fragment[i]=lowest;
barray[parray[i]]=1;
lowest=10000;
}
printf("\nProcess_no\tProcess_size\tBlock_no\tBlock_size\tFragment");
for(i=1;i<=np && parray[i]!=0;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,p[i],parray[i],b[parray[i]],fragment[i]);
}

Output:

69 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

c) First Fit
#include<stdio.h>
#define max 25

int main()

int frag[max],b[max],f[max],i,j,nb,nf,temp;

static int bf[max],ff[max];

printf("\nEnter the number of blocks:");

scanf("%d",&nb);

printf("Enter the number of files:");

scanf("%d",&nf);

printf("\nEnter the size of the blocks:-\n");

for(i=1;i<=nb;i++)

printf("Block %d:",i);

scanf("%d",&b[i]);

printf("Enter the size of the files:-\n");

for(i=1;i<=nf;i++)

printf("File %d:",i);

scanf("%d",&f[i]);

for(i=1;i<=nf;i++)

70 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

for(j=1;j<=nb;j++)

if(bf[j]!=1)

temp=b[j]-f[i];

if(temp>=0)

ff[i]=j;

break;

frag[i]=temp;

bf[ff[i]]=1;

printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragment");

for(i=1;i<=nf;i++)

printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);

return(0);

71 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Output:

RESULT:
Thus the program has been executed successfully and the output is verified.

72 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:06
Page replacement algorithms

Aim:
To write a C program to simulate all page replacement algorithms.

a)FIFO b) LRU c) OPTIMAL

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.c
3. Compile the program using the command cc filename.c -o x.out.
4. Run the program using the command ./x.out.
5. Save the program with extension .c.
6. Stop the program.

73 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
a)FIFO
#include <stdio.h>
int main()
{
int incomingStream[] = {4, 1, 2, 4, 5};
int pageFaults = 0;
int frames = 3;
int m, n, s, pages;

pages = sizeof(incomingStream)/sizeof(incomingStream[0]);

printf("Incoming \t Frame 1 \t Frame 2 \t Frame 3");


int temp[frames];
for(m = 0; m < frames; m++)
{
temp[m] = -1;
}

for(m = 0; m < pages; m++)


{
s = 0;

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


{
if(incomingStream[m] == temp[n])
{
s++;
pageFaults--;
}
}
pageFaults++;

if((pageFaults <= frames) && (s == 0))


{
temp[m] = incomingStream[m];
}
else if(s == 0)
{
temp[(pageFaults - 1) % frames] = incomingStream[m];
}

printf("\n");
printf("%d\t\t\t",incomingStream[m]);
for(n = 0; n < frames; n++)

74 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

{
if(temp[n] != -1)
printf(" %d\t\t\t", temp[n]);
else
printf(" - \t\t\t");
}
}

printf("\nTotal Page Faults:\t%d\n", pageFaults);


return 0;
}

Output:

b)LRU
#include<stdio.h>
int main()
{
int q[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20];
printf("Enter no of pages:");
scanf("%d",&n);
printf("Enter the reference string:");
for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("Enter no of frames:");
scanf("%d",&f);
q[k]=p[k];
printf("\n\t%d\n",q[k]);
c++;
k++;
for(i=1;i<n;i++)
{
c1=0;
for(j=0;j<f;j++)

75 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

{
if(p[i]!=q[j])
c1++;
}
if(c1==f)
{
c++;
if(k<f)
{
q[k]=p[i];
k++;
for(j=0;j<k;j++)
printf("\t%d",q[j]);
printf("\n");
}
else
{
for(r=0;r<f;r++)
{
c2[r]=0;
for(j=i-1;j<n;j--)
{
if(q[r]!=p[j])
c2[r]++;
else
break;
}
}
for(r=0;r<f;r++)
b[r]=c2[r];
for(r=0;r<f;r++)
{
for(j=r;j<f;j++)
{
if(b[r]<b[j])
{
t=b[r];
b[r]=b[j];
b[j]=t;
}
}
}
for(r=0;r<f;r++)
{
if(c2[r]==b[0])
q[r]=p[i];
printf("\t%d",q[r]);

76 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

}
printf("\n");
}
}
}
printf("\nThe no of page faults is %d",c);
}

Output:

c)Optimal
#include<stdio.h>
int main()
{
int no_of_frames, no_of_pages, frames[10], pages[30], temp[10], flag1, flag2, flag3, i, j, k,
pos, max, faults = 0;
printf("Enter number of frames: ");
scanf("%d", &no_of_frames);

printf("Enter number of pages: ");


scanf("%d", &no_of_pages);

printf("Enter page reference string: ");

for(i = 0; i < no_of_pages; ++i){


scanf("%d", &pages[i]);
}

for(i = 0; i < no_of_frames; ++i){


frames[i] = -1;

77 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

for(i = 0; i < no_of_pages; ++i){


flag1 = flag2 = 0;

for(j = 0; j < no_of_frames; ++j){


if(frames[j] == pages[i]){
flag1 = flag2 = 1;
break;
}
}

if(flag1 == 0){
for(j = 0; j < no_of_frames; ++j){
if(frames[j] == -1){
faults++;
frames[j] = pages[i];
flag2 = 1;
break;
}
}
}

if(flag2 == 0){
flag3 =0;

for(j = 0; j < no_of_frames; ++j){


temp[j] = -1;

for(k = i + 1; k < no_of_pages; ++k){


if(frames[j] == pages[k]){
temp[j] = k;
break;
}
}
}

for(j = 0; j < no_of_frames; ++j){


if(temp[j] == -1){
pos = j;
flag3 = 1;
break;
}
}

if(flag3 ==0){
max = temp[0];

78 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

pos = 0;

for(j = 1; j < no_of_frames; ++j){


if(temp[j] > max){
max = temp[j];
pos = j;
}
}
}
frames[pos] = pages[i];
faults++;
}

printf("\n");

for(j = 0; j < no_of_frames; ++j){


printf("%d\t", frames[j]);
}
}

printf("\n\nTotal Page Faults = %d", faults);

return 0;
}

Output:

RESULT:
Thus the program has been executed successfully and the output is verified.

79 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:07
File organization techniques

Aim:
To write a C program to simulate all File Organization Techniques.

a) Single level directory b) Two level directory

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.c
3. Compile the program using the command cc filename.c -o x.out.
4. Run the program using the command ./x.out.
5. Save the program with extension .c.
6. Stop the program.

80 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
a)Single level directory
#include<stdio.h>
#include<string.h>
int main()
{
int nf=0,i=0,j=0,ch;
char mdname[10],fname[10][10],name[10];

printf("Enter the directory name:");


scanf("%s",mdname);
printf("Enter the number of files:");
scanf("%d",&nf);
do
{
printf("Enter file name to be created:");
scanf("%s",name);
for(i=0;i<nf;i++)
{
if(!strcmp(name,fname[i]))
break;
}
if(i==nf)
{
strcpy(fname[j++],name);
nf++;
}
else
printf("There is already %s\n",name);
printf("Do you want to enter another file(yes - 1 or no - 0):");
scanf("%d",&ch);
}
while(ch==1);
printf("Directory name is:%s\n",mdname);
printf("Files names are:");
for(i=0;i<j;i++)
printf("\n%s",fname[i]);
return 0;
}

81 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Output:

b)Two level directory


#include<string.h>
#include<stdlib.h>
#include<stdio.h>
struct
{
char dname[10],fname[10][10];
int fcnt;
}dir[10];
void main()
{
int i,ch,dcnt,k;
char f[30], d[30];
dcnt=0;
while(1)
{
printf("\n\n1. Create Directory\t2. Create File\t3. Delete File");
printf("\n4. Search File\t\t5. Display\t6. Exit\tEnter your choice -- ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter name of directory -- ");
scanf("%s", dir[dcnt].dname);
dir[dcnt].fcnt=0;
dcnt++;
printf("Directory created");
break;
case 2: printf("\nEnter name of the directory -- ");
scanf("%s",d);

82 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

for(i=0;i<dcnt;i++)
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file -- ");
scanf("%s",dir[i].fname[dir[i].fcnt]);
printf("File created");
break;
}
if(i==dcnt)
printf("Directory %s not found",d);
break;
case 3: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file -- ");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{
printf("File %s is deleted ",f);
dir[i].fcnt--;
strcpy(dir[i].fname[k],dir[i].fname[dir[i].fcnt]);
goto jmp;
}
}
printf("File %s not found",f);
goto jmp;
}
}
printf("Directory %s not found",d);
jmp : break;
case 4: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter the name of the file -- ");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{

83 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

printf("File %s is found ",f);


goto jmp1;
}
}
printf("File %s not found",f);
goto jmp1;
}
}
printf("Directory %s not found",d);
jmp1: break;
case 5: if(dcnt==0)
printf("\nNo Directory's ");
else
{
printf("\nDirectory\tFiles");
for(i=0;i<dcnt;i++)
{
printf("\n%s\t\t",dir[i].dname);
for(k=0;k<dir[i].fcnt;k++)
printf("\t%s",dir[i].fname[k]);
}
}
break;
default:exit(0);
}
}
}

84 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Output:

RESULT:
Thus the program has been executed successfully and the output is verified.

85 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:08
File allocation strategies

Aim:
To write a C program to simulate all file allocation strategies.

a) Sequential b) Indexed c) Linked.

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.c
3. Compile the program using the command cc filename.c -o x.out.
4. Run the program using the command ./x.out.
5. Save the program with extension .c.
6. Stop the program.

86 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
a)Sequential
#include<stdio.h>
int main()
{
int f[50],i,st,j,len,c,k;
for(i=0;i<50;i++)
f[i]=0;
X:
printf("\n Enter the starting block & length of file");
scanf("%d%d",&st,&len);
for(j=st;j<(st+len);j++)
if(f[j]==0)
{
f[j]=1
;
printf("\n%d->%d",j,f[j]);
}
else
{
printf("Block already allocated");
break;
}
if(j==(st+len))
printf("\n the file is allocated to disk");
printf("\n if u want to enter more files?(y-1/n-0)");
scanf("%d",&c);
if(c==1)
goto X;
else
return(0);
}

87 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Output:

b) Indexed
#include<stdio.h>
int f[50],i,k,j,inde[50],n,c,count=0,p;
int main()
{
for(i=0;i<50;i++)
f[i]=0;
x: printf("enter index block\t");
scanf("%d",&p);
if(f[p]==0)
{
f[p]=1;
printf("enter no of files on index\t");
scanf("%d",&n);
}
else
{
printf("Block already allocated\n");
goto x;
}
for(i=0;i<n;i++)
scanf("%d",&inde[i]);
for(i=0;i<n;i++)
if(f[inde[i]]==1)
{
printf("Block already allocated");

88 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

goto x;
}
for(j=0;j<n;j++)
f[inde[j]]=1;
printf("\n allocated");
printf("\n file indexed");
for(k=0;k<n;k++)
printf("\n %d->%d:%d",p,inde[k],f[inde[k]]);
printf(" Enter 1 to enter more files and 0 to exit\t");
scanf("%d",&c);
if(c==1)
goto x;
else
return(0);
}

Output:

89 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

c) Linked
#include<stdio.h>
int main()
{
int f[50],p,i,j,k,a,st,len,n,c;

for(i=0;i<50;i++) f[i]=0;
printf("Enter how many blocks that are already allocated");
scanf("%d",&p);
printf("\nEnter the blocks no.s that are already allocated");
for(i=0;i<p;i++)
{
scanf("%d",&a);
f[a]=1;
}
X:
printf("Enter the starting index block & length");
scanf("%d%d",&st,&len);
k=len;
for(j=st;j<(k+st);j++)
{
if(f[j]==0)
{ f[j]=1;
printf("\n%d->%d",j,f[j]);
}
else
{
printf("\n %d->file is already allocated",j);
k++;
}
}
printf("\n If u want to enter one more file? (yes-1/no-0)");
scanf("%d",&c);
if(c==1)
goto
X;
else
return(0);
}

90 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Output:

RESULT:
Thus the program has been executed successfully and the output is verified.

91 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:09
Deadlock avoidance

Aim:
To write a C program to simulate Bankers Algorithm for DeadLock Avoidance.

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.c
3. Compile the program using the command cc filename.c -o x.out.
4. Run the program using the command ./x.out.
5. Save the program with extension .c.
6. Stop the program.

92 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
#include <stdio.h>
int main()
{
// P0, P1, P2, P3, P4 are the Process names here
int n, m, i, j, k;
n = 5; // Number of processes
m = 3; // Number of resources
int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix
{ 2, 0, 0 }, // P1
{ 3, 0, 2 }, // P2
{ 2, 1, 1 }, // P3
{ 0, 0, 2 } }; // P4
int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix
{ 3, 2, 2 }, // P1
{ 9, 0, 2 }, // P2
{ 2, 2, 2 }, // P3
{ 4, 3, 3 } }; // P4

int avail[3] = { 3, 3, 2 }; // Available Resources

int f[n], ans[n], ind = 0;


for (k = 0; k < n; k++) {
f[k] = 0;
}
int need[n][m];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
}
int y = 0;
for (k = 0; k < 5; k++) {
for (i = 0; i < n; i++) {
if (f[i] == 0) {

int flag = 0;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]){
flag = 1;
break;
}
}

if (flag == 0) {
ans[ind++] = i;
for (y = 0; y < m; y++)

93 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}

int flag = 1;

for(int i=0;i<n;i++)
{
if(f[i]==0)
{
flag=0;
printf("The following system is not safe");
break;
}
}

if(flag==1)
{
printf("Following is the SAFE Sequence\n");
for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);
printf(" P%d", ans[n - 1]);
}

return (0);

Output:

RESULT:
Thus the program has been executed successfully and the output is verified.

94 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:10
Deadlock Prevention

Aim:
To write a C program to simulate Bankers Algorithm for DeadLock Prevention.

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.c
3. Compile the program using the command cc filename.c -o x.out.
4. Run the program using the command ./x.out.
5. Save the program with extension .c.
6. Stop the program.

95 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
#include<stdio.h>
int main()
{
int allocated[15][15],max[15][15],need[15][15],avail[15],tres[15],work[15],flag[15];
int pno,rno,i,j,prc,count,t,total;
count=0;
printf("\n Enter number of process:");
scanf("%d",&pno);
printf("\n Enter number of resources:");
scanf("%d",&rno);
for(i=1;i<=pno;i++)
{
flag[i]=0;
}
printf("\n Enter total numbers of each resources:");
for(i=1;i<= rno;i++)
scanf("%d",&tres[i]);

printf("\n Enter Max resources for each process:");


for(i=1;i<= pno;i++)
{
printf("\n for process %d:",i);
for(j=1;j<= rno;j++)
scanf("%d",&max[i][j]);
}

printf("\n Enter allocated resources for each process:");


for(i=1;i<= pno;i++)
{
printf("\n for process %d:",i);
for(j=1;j<= rno;j++)
scanf("%d",&allocated[i][j]);

printf("\n available resources:\n");


for(j=1;j<= rno;j++)
{
avail[j]=0;
total=0;
for(i=1;i<= pno;i++)
{

96 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

total+=allocated[i][j];
}
avail[j]=tres[j]-total;
work[j]=avail[j];
printf(" %d \t",work[j]);
}

do
{

for(i=1;i<= pno;i++)
{
for(j=1;j<= rno;j++)
{
need[i][j]=max[i][j]-allocated[i][j];
}
}

printf("\n Allocated matrix Max need");


for(i=1;i<= pno;i++)
{
printf("\n");
for(j=1;j<= rno;j++)
{
printf("%4d",allocated[i][j]);
}
printf("|");
for(j=1;j<= rno;j++)
{
printf("%4d",max[i][j]);
}
printf("|");
for(j=1;j<= rno;j++)
{
printf("%4d",need[i][j]);
}
}

prc=0;

for(i=1;i<= pno;i++)

97 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

{
if(flag[i]==0)
{
prc=i;

for(j=1;j<= rno;j++)
{
if(work[j]< need[i][j])
{
prc=0;
break;
}
}
}

if(prc!=0)
break;
}

if(prc!=0)
{
printf("\n Process %d completed",i);
count++;
printf("\n Available matrix:");
for(j=1;j<= rno;j++)
{
work[j]+=allocated[prc][j];
allocated[prc][j]=0;
max[prc][j]=0;
flag[prc]=1;
printf(" %d",work[j]);
}
}

}while(count!=pno&&prc!=0);

if(count==pno)
printf("\nThe system is in a safe state!!");
else
printf("\nThe system is in an unsafe state!!");

return 0;
}

98 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Output:

99 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

RESULT:
Thus the program has been executed successfully and the output is verified.

100 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Ex no:11
Disk scheduling algorithms

Aim:
To write a C program to simulate disk scheduling algorithms.

a) FCFS b) SCAN c) C-SCAN

Algorithm:
1. Start the Program
2. Type the codings in Text editor using the command gedit filename.c
3. Compile the program using the command cc filename.c -o x.out.
4. Run the program using the command ./x.out.
5. Save the program with extension .c.
6. Stop the program.

101 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Source code:
a)FCFS
#include<stdio.h>
#include<stdlib.h>
int main()
{
int RQ[100],i,n,TotalHeadMoment=0,initial;
printf("Enter the number of Requests\n");
scanf("%d",&n);
printf("Enter the Requests sequence\n");
for(i=0;i<n;i++)
scanf("%d",&RQ[i]);
printf("Enter initial head position\n");
scanf("%d",&initial);

// logic for FCFS disk scheduling

for(i=0;i<n;i++)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];
}

printf("Total head moment is %d",TotalHeadMoment);


return 0;

Output:

102 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

b)SCAN
#include<stdio.h>
#include<stdlib.h>
int main()
{
int RQ[100],i,j,n,TotalHeadMoment=0,initial,size,move;
printf("Enter the number of Requests\n");
scanf("%d",&n);
printf("Enter the Requests sequence\n");
for(i=0;i<n;i++)
scanf("%d",&RQ[i]);
printf("Enter initial head position\n");
scanf("%d",&initial);
printf("Enter total disk size\n");
scanf("%d",&size);
printf("Enter the head movement direction for high 1 and for low 0\n");
scanf("%d",&move);

// logic for Scan disk scheduling

/*logic for sort the request array */


for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(RQ[j]>RQ[j+1])
{
int temp;
temp=RQ[j];
RQ[j]=RQ[j+1];
RQ[j+1]=temp;
}

}
}

int index;
for(i=0;i<n;i++)
{
if(initial<RQ[i])
{
index=i;
break;
}
}

103 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

// if movement is towards high value


if(move==1)
{
for(i=index;i<n;i++)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];
}
// last movement for max size
TotalHeadMoment=TotalHeadMoment+abs(size-RQ[i-1]-1);
initial = size-1;
for(i=index-1;i>=0;i--)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];

}
}
// if movement is towards low value
else
{
for(i=index-1;i>=0;i--)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];
}
// last movement for min size
TotalHeadMoment=TotalHeadMoment+abs(RQ[i+1]-0);
initial =0;
for(i=index;i<n;i++)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];

}
}

printf("Total head movement is %d",TotalHeadMoment);


return 0;
}

104 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

Output:

C) C-Scan

#include<stdio.h>
#include<stdlib.h>
int main()
{
int RQ[100],i,j,n,TotalHeadMoment=0,initial,size,move;
printf("Enter the number of Requests\n");
scanf("%d",&n);
printf("Enter the Requests sequence\n");
for(i=0;i<n;i++)
scanf("%d",&RQ[i]);
printf("Enter initial head position\n");
scanf("%d",&initial);
printf("Enter total disk size\n");
scanf("%d",&size);
printf("Enter the head movement direction for high 1 and for low 0\n");
scanf("%d",&move);

// logic for C-Scan disk scheduling

/*logic for sort the request array */


for(i=0;i<n;i++)
{
for( j=0;j<n-i-1;j++)
{
if(RQ[j]>RQ[j+1])
{

105 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

int temp;
temp=RQ[j];
RQ[j]=RQ[j+1];
RQ[j+1]=temp;
}

}
}

int index;
for(i=0;i<n;i++)
{
if(initial<RQ[i])
{
index=i;
break;
}
}

// if movement is towards high value


if(move==1)
{
for(i=index;i<n;i++)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];
}
// last movement for max size
TotalHeadMoment=TotalHeadMoment+abs(size-RQ[i-1]-1);
/*movement max to min disk */
TotalHeadMoment=TotalHeadMoment+abs(size-1-0);
initial=0;
for( i=0;i<index;i++)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];

}
}
// if movement is towards low value
else
{
for(i=index-1;i>=0;i--)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];
}

106 SACWC
PYTHON PROGRAMMING & OPERATING SYSTEM LAB JUNE 2022

// last movement for min size


TotalHeadMoment=TotalHeadMoment+abs(RQ[i+1]-0);
/*movement min to max disk */
TotalHeadMoment=TotalHeadMoment+abs(size-1-0);
initial =size-1;
for(i=n-1;i>=index;i--)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];

}
}

printf("Total head movement is %d",TotalHeadMoment);


return 0;
}

Output:

RESULT:
Thus the program has been executed successfully and the output is verified.

107 SACWC

You might also like