Python Lab Manual
Python Lab Manual
2.
Producer-Consumer Problem using Semaphores
9. Deadlock Avoidance
PYTHON PROGRAMMING
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. Open Text Editor using the command gedit filename.py (gedit error.py) and type
the Python Scripts.
3. Save the program with extension .py.
4. Run the program using the command python3 filename.py (python3 errror.py)
5. Stop the program.
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")) ifn1>n2:
print("n1 is big")
else:
print("n2isbig")
OUTPUT:
Lakshmi.S, Assistant Professor, Dept. of Computer Science, SACWC. | 4
PYTHON PROGRAMMING & OPERATING
SYSTEM LAB November 3, 2023
[Correct code]
n1=int(input("enter n1
value")) n2=int(input("enter
n1 value")) ifn1>n2:
print("n1 is big")
else:
print("n2isbig")
OUTPUT:
RESULT:
Thus the program has been executed successfully and the output is verified.
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. Open Text Editor using the command gedit filename.py and type the Python Scripts.
3. Get input values for x1,x2,y1,y2 and perform the operations (x2-x1)*(x2-x1)
, (y2 - y1) * (y2 - y1).
4. After performing the operations, the distance between two points is obtained.
5. Save the program with extension .py.
6. Run the program using the command python3 filename.py
7. Stop the program.
SOURCE CODE:
a) DISTANCE
import math;
x1=int(input("Enterx1---
>"))
y1=int(input("Entery1--->"))
x2=int(input("Enterx2--->"))
y2=int(input("Entery2--->"))
d1=(x2-x1)*(x2-x1);
d2 = (y2 - y1) * (y2 - y1);
res=math.sqrt(d1+d2)
print("Distancebetweentwopoints:",res)
;
OUTPUT:
RESULT:
Thus the program has been executed successfully and the output is verified.
EX NO:03
CONTROL FLOW
AIM:
a. Write a Program for checking whether the given number is aeven 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
d. Write a program using a while loop that asks the user for a number, and prints a
countdown from that number to zero.
ALGORITHM:
1. Start the Program
2. Open Text Editor using the command gedit filename.py and type the Python Scripts.
3. Get input value for n and check the condition (n%2==0) for finding the given
number is odd or even.
4. To print the decimal equivalents, the for loop in range is used.
5. Save the program with extension .py.
6. Run the program using the command python3 filename.py
7. Stop the program.
SOURCE CODE:
a) EVEN
n=int(input("Enter a number-------------->"))
ifn%2==0:
print ("EVEN Number");
else:
print("ODD Number");
OUTPUT:
b) DECIMAL
i=1;
for j in range(2,10):
print("i:",i,"j:",j
) print(i,"/",j)
print(i/j);
OUTPUT:
c) SEQUENCE
str = "i am python
developer" for I in str:
print(i)
OUTPUT:
D) WHILELOOP
n = int(input("Enter A Number---
>")); whilen>=0:
print (n);
n=n-1;
OUTPUT:
e) FIBONACCI
a,b=1,2
total = 0
print(a,end="
")
while(a<=2000000-1):
ifa%2!
=0:total+=a a, b
= b, a+b
print(a,end=" ")
print("\n sum of prime numbers term in Fibonacci series:",total)
OUTPUT:
f) FIBONACCI SERIES
a,b=1,2
total = 0
print(a,end="
")
while(a<=4000000-1):
ifa
%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:
Lakshmi.S, Assistant Professor, Dept. of Computer Science, SACWC. | 16
PYTHON PROGRAMMING & OPERATING
SYSTEM LAB November 3, 2023
Thus the program has been executed successfully and the output is verified.
EX NO:04
DATA STRUCTURE
AIM:
a. Write a program to count the numbers of characters in the string and
store them in a dictionary data structure
b. Write a program to use split and join methods in the string and trace
a birthday with a dictionary data structure.
c. Write a program combine lists that combines these lists into a dictionary.
ALGORITHM:
1. Start the Program
2. Open Text Editor using the command gedit filename.py and type the Python Scripts.
3. Get the input string to count the number of characters.
4. Declare a, b, c to split and join the given string.
5. Declare l, k, and m to combine the list into dictionary.
6. Save the program with extension .py.
7. Run the program using the command python3 filename.py
8. Stop the program.
SOURCE CODE:
a) COUNT
str=input("Enter a
String:") dict={}
for n in str:
keys =
dict.keys()ifninkeys:
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:
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.
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.
ALGORITHM:
1. Start the Program
2. Open Text Editor using the command gedit filename.py and type the Python Scripts.
3. For ball colliding, we have to import math module function.
4. To find mean, median , mode, we have to import from statistics import math
module function.
5. Save the program with extension .py.
6. Run the program using the command python3 filename.py
7. Stop the program.
17
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:
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
SequenceMatcher
defNearly_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("aismutationonb")
else:
print("BothStringsareDifferent")
OUTPUT:
d)
def FindDuplicates(list):
for I in list:
count=list.count(i
) ifcount>1:
print('There are duplicates in list')
returnTrue
print ('There are no duplicates in
list') returnFalse
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:
e)
def FindUnique(list):
unique =
set(list)
foriinunique:
count=list.count(i)
ifcount>1:
print('Therearenouniqueelementsinlist')
returnTrue
print ('There are unique elements in
list') returnFalse
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.
Lakshmi.S, Assistant Professor, Dept. of Computer Science, SACWC. | 30
PYTHON PROGRAMMING & OPERATING
SYSTEM LAB November 3, 2023
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. Open Text Editor using the command gedit filename.py and type the Python Scripts.
3. Get the input values for n1 and n2 to find GCD and LCM values.
4. Save the program with extension .py.
5. Run the program using the command python3 filename.py
6. Stop the program.
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:
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)
Lakshmi.S, Assistant Professor, Dept. of Computer Science, SACWC. | 33
PYTHON PROGRAMMING & OPERATING
SYSTEM LAB November 3, 2023
OUTPUT:
RESULT:
Thus the program has been executed successfully and the output is verified.
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. Open Text Editor using the command gedit filename.py and type the Python Scripts.
3. Perform the operations for matrix to define a matrix, addition of two square
matrices and multiplication of two square matrices.
4. Get the input values for row and column for 1st and 2nd matrix.
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
2ndMatrix:")) 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("2stMatrixY:",Y)
OUTPUT:
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("EnterNoofcolumnfor2ndMatrix:"))
X=[[int(input(("EntervalueforX[",i,"][",j,"]:")))
forjinrange(column)]foriinrange(row)]
Y=[[int(input(("EntervalueforY[",i,"][",j,"]:")))
forjinrange(column1)]foriinrange(row1)]
print("1st Matrix
X:",X)print("2stMatrixY:",Y)
if(row==row1andcolumn==column1):
result=[[X[i][j]+Y[i]
[j] forjinrange(len(X))]
for
iinrange(len(X[0
]))] print(result)
else:
print("Adition2MatrixnotPossible")
OUTPUT:
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("EnterNoofcolumnfor2ndMatrix:"))
if(column==row1):
X=[[int(input(("EntervalueforX[",i,"][",j,"]:")))
forjinrange(column)
] foriinrange(row)]
Y=[[int(input(("EntervalueforY[",i,"][",j,"]:")))
forjinrange(column1)]
foriinrange(row1)]
result=[[0forjinrange(column1)
] foriinrange(row)]
print("result",result)
print("1st Matrix
X:",X) print("2st
Matrix Y:",Y)
foriinrange(len(X)):
for j in
range(len(Y[0])):
forkinrange(len(Y)):
result[i][j]+=X[i][k]*Y[k][j]
for r in result:print(r)
else:
print("Multiplicationisnotpossible")
OUTPUT:
RESULT:
Thus the program has been executed successfully and the output is verified.
EX NO:08
OBJECT ORIENTED
PROGRAMMING
AIM:
a) Class variables and instance variable and illustration of these lf variable
i) Robot
ALGORITHM:
1. Start the Program
2. Open Text Editor using the command gedit filename.py and type the Python Scripts.
3. Perform the operations for initializing and destroying the robots.
4. Perform the operations to check the bank balance, withdraw and deposit of money.
5. Save the program with extension .py.
6. Run the program using the command python3 filename.py
7. Stop the program.
SOURCE CODE:
a)
class Robot:
population=0
def init(self, name):
self.name=name
print('(Initializing{0})'.format(self.name))
Robot.population += 1defdel(self):
print('{0}isbeingdestroyed!'.format(self.name))
Robot.population-=1
if Robot.population==0:
print('{0}wasthelastone.'.format(self.name))
else:
print('There are still {0:d}
robotsworking.'.format(Robot.population))
defsayHi(self):
print('Greetings,mymasterscallme{0}.'.format(self.name))
defhowMany():
print('We have
{0:d}robots.'.format(Robot.population)
) howMany = static
method(howMany)d=Robot('R1-D1')
d.sayHi()
Robot.howMany(
) d1=Robot('R2-
D2')
d1.sayHi()Robot.howMany()
print("\n Robots can do some work here.\n")
print("Robots have finished their work.Solet's destroy
them.") del d
deld1
Robot.howMany(
)
OUTPUT:
b)
class Bank:
Account_type =
"Savings" location
="Guntur"
definit(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
defrepr(self):
print("WelcometotheSBIATMMachine")
print(" "
)
account_pin=int(input("Pleaseenteryourpinnumber")
) if(account_pin==123):
Account(self
) else:
print("PinIncorrect.Pleasetryagain")
Error(self)
return ' '.join([self.name,self.Account_Number])
defError(self):
account_pin=int(input("Pleaseenteryourpinnumber")
if(account_pin==123)
: Account(self)
else:
print("PinIncorrect.Pleasetryagain")
Error(self)
defAccount(self):
print("YourCardNumberis:XXXXXXXXXXXX1337")
print("Wouldyouliketodeposit/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)
: =
4): Deposit(self)elif(option==
exit()
def Balance(self):
print("Balance:",self.balance)Account(self
) defWithdraw(self):
w=int(input("Please Enter Desired amount:
")) if(self.balance>0andself.balance>=w):
self.balance=self.balance-w
print("Yourtransactionissuccessfull")
print("your Balance:",self.balance)
print("")
else:
print("Your transaction is cancelled due to")
print("Amountisnotsufficientinyouraccount")
Account(self)
defDeposit(self):
d=int(input("Please Enter Desired
amount: "))self.balance=self.balance+d
print("Your transaction is
successfull")print("Balance:",self.balance)Account(self)
defExit():
print("Exit")
t1 = Bank('mahesh', 1453210145,5000)print(t1)
OUTPUT:
RESULT:
Thus the program has been executed successfully and the output is verified.
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. Open Text Editor using the command gedit filename.py and type the Python Scripts.
3. Save the program with extension .py.
4. Run the program using the command python3 filename.py
5. Stop the program.
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
unittestdefreverse(s):
returns[::-1]
class
Test(unittest.TestCase):
deftest_reverse(self):
s="mahesh"
print( reverse(s))self.assertEqual("hseham",reverse(s)
) unittest.main()
OUTPUT:
RESULT:
Thus the program has been executed successfully and the output is verified.
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. Open Text Editor using the command gedit filename.py and type the Python Scripts.
3. Get the input values for the items to be inserted into the stack.
4. Save the program with extension .py.
5. Run the program using the command python3 filename.py
6. Stop the program.
SOURCE CODE:
a)
class Stack:
# initialize an empty list
(stack) definit(self):
self.mStack=[]
# function to check if the stack is
empty defisEmpty(self):
returnself.mStack==[]
ifname =="main":
# create an instance of the stack
Lakshmi.S, Assistant Professor, Dept. of Computer Science, SACWC. | 56
PYTHON PROGRAMMING & OPERATING
SYSTEM LAB November 3, 2023
class mStack=Stack()
print(" "
) print( "Implementation of Stack in Python")print("
---")
print("Menuitems")
print("1.Viewthestack"
)
print ("2. Pushitem intostack")
print ("3. Pop item out of
stack") print ("4. Get the size of
stack")
print("5.Getthetopiteminstack")
print("6.Quittheprogram")
whileTrue:
user_input=int(input("Entertheoption:"))
ifuser_input==1:mStack.view(
) elifuser_input==2:
item=(input("Entertheitemtobeinserted:")
) mStack.push(item)
elifuser_input==3:mStack.pop()
elif user_input ==
4:
print(mStack.size()
) elif user_input ==
5:
print(mStack.top())
elifuser_input==6:
break
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)
)
OUTPUT:
RESULT:
Thus the program has been executed successfully and the output is verified.
OPERATING SYSTEM
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. Open Text Editor using the command gedit filename.c and type the C codings.
3. Get the input values for number of processes and the burst time for process.
4. Save the program with extension .c.
5. Compile the program using the command cc filename.c -o x.out.
6. Run the program using the command ./x.out.
7. Stop the program.
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);
}
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];
Lakshmi.S, Assistant Professor, Dept. of Computer Science, SACWC. | 67
PYTHON PROGRAMMING & OPERATING
SYSTEM LAB November 3, 2023
p[k]=temp;
}
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("\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:
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);
Lakshmi.S, Assistant Professor, Dept. of Computer Science, SACWC. | 71
PYTHON PROGRAMMING & OPERATING
SYSTEM LAB November 3, 2023
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;
}
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.
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. Open Text Editor using the command gedit filename.c and type the C codings.
3. Get the input values to item for producer and consumer.
4. Save the program with extension .c.
5. Compile the program using the command cc filename.c -o x.out.
6. Run the program using the command ./x.out.
7. Stop the program.
SOURCE CODE:
#include
<stdio.h>
#include
<stdlib.h>
// Initialize a mutex to
1 int mutex = 1;
// Item
produced x++;
printf("\nProducer
produces" "item %d",
x);
// Driver
Code int
main()
{
int n, i;
printf("\n1. Press 1 for
Producer" "\n2. Press 2 for
Consumer" "\n3. Press 3 for
Exit");
printf("\nEnter your
choice:"); scanf("%d", &n);
// Switch
Cases switch
(n) { case 1:
// possible to
produce if ((mutex
== 1)
; case
2:
// Exit
Condition case
3:
exit(0)
;
break;
}
}
}
OUTPUT:
RESULT:
Thus the program has been executed successfully and the output is verified.
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. Open Text Editor using the command gedit filename.c and type the C codings.
3. Save the program with extension .c.
4. Compile the program using the command cc filename.c -o x.out.
5. Run the program using the command ./x.out.
6. Stop the program.
SOURCE CODE:
#include<stdio.h
> #define n 4
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);
if(otherFork== -1)
otherFork=(n-
1);
}else{
printf("Philosopher %d is waiting for fork %d\n",philID+1,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
Lakshmi.S, Assistant Professor, Dept. of Computer Science, SACWC. | 88
PYTHON PROGRAMMING & OPERATING
SYSTEM LAB November 3, 2023
return 0;
OUTPUT:
RESULT:
Thus the program has been executed successfully and the output is verified.
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. Open Text Editor using the command gedit filename.c and type the C codings.
3. Get the input values for total memory available ant memory required for processes.
4. Save the program with extension .c.
5. Compile the program using the command cc filename.c -o x.out.
6. Run the program using the command ./x.out.
7. Stop the program.
SOURCE CODE:
MVT:
#include<stdio.h
return 0;
}
OUTPUT:
MFT:
#include<stdio.h
> int main()
{
int ms, bs, nob, ef,n,
mp[10],tif=0; int i,p=0;
return 0;
}
OUTPUT:
RESULT:
Thus the program has been executed successfully and the output is verified.
EX NO:05
MEMORY ALLOCATION TECHNIQUES
AIM:
Write a C program to simulate the following contiguous memory allocation Techniques.
ALGORITHM:
1. Start the Program
2. Open Text Editor using the command gedit filename.c and type the C codings.
3. Get the input values for number of files and number of blocks or processes.
4. Save the program with extension .c.
5. Compile the program using the command cc filename.c -o x.out.
6. Run the program using the command ./x.out.
7. Stop the program.
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
Lakshmi.S, Assistant Professor, Dept. of Computer Science, SACWC. | 98
PYTHON PROGRAMMING & OPERATING
SYSTEM LAB November 3, 2023
%d",i,f[i],ff[i],b[ff[i]],frag[i]);
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);
Lakshmi.S, Assistant Professor, Dept. of Computer Science, SACWC. | 100
PYTHON PROGRAMMING & OPERATING
SYSTEM LAB November 3, 2023
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:
c) First Fit
#include<stdio.h> #define max 25
int main()
int frag[max],b[max],f[max],i,j,nb,nf,temp;
scanf("%d",&nb);
scanf("%d",&nf);
for(i=1;i<=nb;i++)
printf("Block %d:",i);
scanf("%d",&b[i]);
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:\
%d",i,f[i],ff[i],b[ff[i]],frag[i]); return(0);
OUTPUT:
RESULT:
Thus the program has been executed successfully and the output is verified.
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. Open Text Editor using the command gedit filename.c and type the C codings.
3. Get the input values for number of pages and number of frames.
4. Save the program with extension .c.
5. Compile the program using the command cc filename.c -o x.out.
6. Run the program using the command ./x.out.
7. Stop the program.
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("\n"); printf("%d\t\t\
t",incomingStream[m]); for(n = 0; n <
frames; n++)
{
if(temp[n] != -1)
printf(" %d\t\t\t",
temp[n]); else
printf(" - \t\t\t");
}
}
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++)
{
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]);
}
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);
flag1 = flag2 = 0;
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;
if(flag3 ==0){
max =
temp[0]; pos =
0;
printf("\n");
return 0;
}
OUTPUT:
RESULT:
Thus the program has been executed successfully and the output is verified.
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. Open Text Editor using the command gedit filename.c and type the C codings.
3. Get the input values for Single and Two level directory.
4. Save the program with extension .c.
5. Compile the program using the command cc filename.c -o x.out.
6. Run the program using the command ./x.out.
7. Stop the program.
SOURCE CODE:
OUTPUT:
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)
{
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)
;
}
}
}
OUTPUT:
RESULT:
Thus the program has been executed successfully and the output is verified.
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. Open Text Editor using the command gedit filename.c and type the C codings.
3. Save the program with extension .c.
4. Compile the program using the command cc filename.c -o x.out.
5. Run the program using the command ./x.out.
6. Stop the program.
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)
;
}
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])
;
Lakshmi.S, Assistant Professor, Dept. of Computer Science, SACWC. | 135
PYTHON PROGRAMMING & OPERATING
SYSTEM LAB November 3, 2023
for(i=0;i<n;i++) if(f[inde[i]]==1)
{
printf("Block already
allocated"); 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:
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)
;
}
OUTPUT:
RESULT:
Thus the program has been executed successfully and the output is verified.
EX NO:09
DEADLOCK AVOIDANCE
AIM:
To write a C program to simulate Bankers Algorithm for DeadLock Avoidance.
ALGORITHM:
1. Start the Program
2. Open Text Editor using the command gedit filename.c and type the C codings.
3. Initialize n for number of processes and m for number of resources.
4. Save the program with extension .c.
5. Compile the program using the command cc filename.c -o x.out.
6. Run the program using the command ./x.out.
7. Stop the program.
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 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++)
Lakshmi.S, Assistant Professor, Dept. of Computer Science, SACWC. | 143
PYTHON PROGRAMMING & OPERATING
SYSTEM LAB November 3, 2023
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.
EX NO:10
DEADLOCK PREVENTION
AIM:
To write a C program to simulate Bankers Algorithm for DeadLock Prevention.
ALGORITHM:
1. Start the Program
2. Open Text Editor using the command gedit filename.c and type the C codings.
3. Get the input values for number of processes and number of resources.
4. Save the program with extension .c.
5. Compile the program using the command cc filename.c -o x.out.
6. Run the program using the command ./x.out.
7. Stop the program.
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]);
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];
}
}
prc=0;
for(i=1;i<= pno;i++)
{
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;
}
OUTPUT:
RESULT:
Thus the program has been executed successfully and the output is verified.
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. Open Text Editor using the command gedit filename.c and type the C codings.
3. Get the input values for number of request and the request sequence.
4. Save the program with extension .c.
5. Compile the program using the command cc filename.c -o x.out.
6. Run the program using the command ./x.out.
7. Stop the program.
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);
scheduling for(i=0;i<n;i++)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];
}
OUTPUT:
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);
}
}
int index;
for(i=0;i<n;i+
+)
{
if(initial<RQ[i])
{
index=i
; break;
}
Lakshmi.S, Assistant Professor, Dept. of Computer Science, SACWC. | 155
PYTHON PROGRAMMING & OPERATING
SYSTEM LAB November 3, 2023
}
}
// 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];
}
}
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);
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 low
value else
{
for(i=index-1;i>=0;i--)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];
Lakshmi.S, Assistant Professor, Dept. of Computer Science, SACWC. | 160
PYTHON PROGRAMMING & OPERATING
SYSTEM LAB November 3, 2023
}
}
OUTPUT:
RESULT:
Thus the program has been executed successfully and the output is verified.