0% found this document useful (0 votes)
23 views

Operating System Lab (K)

The document provides details of practical assignments for the 4th semester Operating Systems subject. It includes 12 programming problems covering topics like data types, control structures, functions, arrays, structures and command line arguments.

Uploaded by

Saurav Tiwary
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Operating System Lab (K)

The document provides details of practical assignments for the 4th semester Operating Systems subject. It includes 12 programming problems covering topics like data types, control structures, functions, arrays, structures and command line arguments.

Uploaded by

Saurav Tiwary
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 67

MANAV RACHNA UNIVERSITY, FARIDABAD

Department of Computer Science


Course: B. Tech (CSE) Semester: IVth Session: 2023

Practical File
4th Semester (Academic Year: 2023)
Subject Name: - Operating System
Subject Code: - CSH206-B

Submitted to: - Mr. Anup Singh Kushwaha

Submitted by: - Gorav Rana


Roll No: - 2K22CSUN01078
Branch: - Cse_4b
Department: - B. Tech
Lab 0
1. swap two numbers without using a temporary variable.
#include <stdio.h>

int main() {
int a,b;
printf("Enter the first Number : ");
scanf("%d",&a);

printf("Enter the second number : ");


scanf("%d",&b);

a=a+b;
b=a-b;
a=a-b;

printf("After swapping First Number = %d \n",a);


printf("After swapping second Number = %d ",b);

return 0;
}
Output

2. To Calculate the bill amount for an item given the quantity sold, rate,
discount and tax.
#include <stdio.h>
int main(){
float total_amt,amount, sub_total,discount_amt, tax_amt,qty,val,discount,tax;

printf ("Enter the quantity of item sold: ");


scanf("%f",&qty);

2
printf(" Enter the Price of per item: ");
scanf("%f", & val);
printf("Enter the discount percentage: ");
scanf("%f", &discount);
printf(" Enter the tax: ");
scanf("%f", &tax);

amount = qty * val;


discount_amt = (amount * discount)/100.0;
sub_total = amount - discount_amt;
tax_amt =(sub_total * tax)/100.0;
total_amt = sub_total + tax_amt;
printf("Quantity Sold: %f\n", qty);
printf("Price per item: %f\n",val);
printf("Amount:%f\n",discount_amt);
printf("Discount:%f\n",discount_amt);
printf("After Discounted totalprice of item sold: %f\n", sub_total);
printf("tax: + %f\n", tax_amt);
printf("Total amount %f\n", total_amt);

return 0;

}
Output

3
Based on Decision Control
3. Program to entry any character. If the entered character is in lower case then convert
it into upper case and if it is lower case then convert it into upper case.
#include<stdio.h>
void main(){
char str[20];
int i;
printf("\n enter a string:");
gets(str);
for(i=0;str[i]!='\0';i++) {
if(str[i]>=97 && str[i]<=122)
{
str[i]=str[i]-32;
}
else if(str[i]>=65 && str[i]<=90)
{
str[i]=str[i]+32;
}
}
printf(" %s",str);
return 0;

4
}
OUTPUT

4. To enter a character and determine whether it is vowel or not.


#include <stdio.h>
int main() {
char c;
int lowercase_vowel, uppercase_vowel;
printf("Enter an alphabet: ");
scanf("%c", &c);

lowercase_vowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');

uppercase_vowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');


if (lowercase_vowel || uppercase_vowel)
printf("%c is a vowel.", c);
else
printf("%c is not vowel.", c);
return 0;
}
Output

5. Program to display a menu that offers five options: Readthreenumbers , calculatetotal


,average ,display the smallest and largest value.
#include <stdio.h>
int main() {
float a,b,c;
printf("Enter the first number is a : ");
scanf("%f",&a);
printf("Enter the second number is b : ");

5
scanf("%f",&b);
printf("Enter the third number is c : ");
scanf("%f",&c);

float average=(a+b+c)/3;
float Total=a+b+c;

printf("Calculate total : %f\n",Total);


printf("Calculate Average : %f", average);

if(a>b && a>c){


printf("a is greatest");
}
else{
if(b>a && b>c){
printf("b is greatest\n");
}
else{
printf("c is greatest");
}
}

return 0;

}
Output

Based on Iterative Statements


6. To classify a number as prime or composite.

#include<stdio.h>
int main()
{
int i,n,c=0;
printf ("Enter the number n : ");
scanf ("%d",&n);

6
for (i=1;i<=n;i++)
{
if(n%i==0)
c=c+1;
}
if (c==2)
printf ("The number is PRIME");
else
printf ("The number is COMPOSITE");
return 0;
}
OUTPUT

Based on Functions

7. To find the Fibonacci using recursive function.


#include<stdio.h>
int main(){
int first=0, second=1, i, n, sum=0;
printf("Enter the number of terms: ");
scanf("%d",&n);
printf("Fibonacci Series:");
for(i=0 ; i<n ; i++){
if(i <= 1){
sum=i;
}
else{
sum=first + second;
first=second;
second=sum;
}
printf(" %d",sum);
}
return 0;
7
}
OUTPUT

Based on Arrays

8. To insert a number at a given location in an array.

#include <stdio.h>
int main(){
int arr[100] = { 0 };
int i, x, pos, n = 10;
for (i = 0; i < 10; i++)
arr[i] = i + 1;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
x = 50;
pos = 5;
n++;
for (i = n - 1; i >= pos; i--)
arr[i] = arr[i - 1];
arr[pos - 1] = x;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
OUTPUT

9. In a class there are 10 students. Each student is supposed to appear in three tests.
Write a program using 2D array to print
a. The marks obtained by each student in different subjects.

8
b. Sort the average obtained by each student.

#include <stdio.h>
int main() {
int i, j, k, temp;
float marks[10][3], avg[10];
printf("Enter the marks of each student in three tests:\n");
for (i = 0; i < 10; i++) {
printf("Student %d:\n", i + 1);
for (j = 0; j < 3; j++) {
printf("Test %d: ", j + 1);
scanf("%f", &marks[i][j]);
}
}
for (i = 0; i < 10; i++) {
avg[i] = 0;
for (j = 0; j < 3; j++) {
avg[i] += marks[i][j];
}
avg[i] /= 3;
}
printf("Marks obtained by each student in different subjects:\n");
for (i = 0; i < 10; i++) {
printf("Student %d: ", i + 1);
for (j = 0; j < 3; j++) {
printf("%.2f ", marks[i][j]);
}
printf("\n");
}
for (i = 0; i < 10; i++) {
for (j = i + 1; j < 10; j++) {
if (avg[i] < avg[j]) {
temp = avg[i];
avg[i] = avg[j];
avg[j] = temp;
9
for (k = 0; k < 3; k++) {
temp = marks[i][k];
marks[i][k] = marks[j][k];
marks[j][k] = temp;
}
}
}
}
printf("\nSorted average obtained by each student:\n");
for (i = 0; i < 10; i++) {
printf("Student %d: %.2f\n", i + 1, avg[i]);
}
return 0;
}

OUTPUT

10
11
10.Accept any two strings from the user. Display whether both the strings are equal or
not. (do not use standard functions).
#include <stdio.h>
int main (){
int count1 = 0, count2 = 0, flag = 0, i;
char string1[30], string2[30];
printf ("Enter the First string : ");
gets (string1);

printf ("Enter the Second string : ");


gets (string2);
while (string1[count1] != '\0')
count1 ++;
while (string2[count2] != '\0')
count2 ++;
i = 0;
while (string1[i] == string2[i] && string1[i] != '\0') {
i ++;
}
if (string1[i] != string2[i])
printf ("Both strings are not equal\n");
else
printf ("Both strings are equal\n");
return 0;
12
}

OUTPUT

Based on Structures

11.Write a program to accept a list of 10 integers in an array, pass the starting address of
array in sum function, calculate the sum of the array elements in the function and
return the sum calculated in the main function.
#include <stdio.h>
int sum_of_elements(int *arr , int n)
{
int i=0,sum=0;
for(i=0; i<n ; i++)
{
sum = sum + arr[i];
}
return sum;
}

int main(){
int total = 0;
int array[10] = {1,2,3,4,5,6,7,8,9};
total = sum_of_elements(array,9);
printf("\nThe sum of all array elements is : %d",total);
return 0;
}
OUTPUT

Based on Command Line Arguments

12.Program to add two numbers using Command Line Arguments.

13
#include <stdio.h>
int main(int argc, char *argv[]){
int a,b,sum;
if(argc!=3)
{
printf("please use \"prg_name value1 value2 \"\n");
return -1;
}
a = atoi(argv[1]);
b = atoi(argv[2]);
sum = a+b;
printf("Sum of %d, %d is: %d\n",a,b,sum);
return 0;
}
OUTPUT

DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY


14
Lab-1
Laboratory Objective: To implement Basic system calls of UNIX Operating
System
Learning Outcome: Familiarity with the use of basic calls of UNIX

Course Outcome: CO2


Blooms Taxonomy: BT1, BT2, BT3
Write programs using the following system calls of UNIX operating system
1. fork()

2. exec()

3. getpid()

4. exit()

5. wait()

Program
#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/wait.h>

int main() {

pid_t pid;

int status;

pid = fork();

if (pid < 0) {

fprintf(stderr, "Fork failed.\n");

return 1;

} else if (pid == 0) {

15
printf("Child process - PID: %d\n", getpid());

char *args[] = {"/bin/ls", "-l", NULL};

execvp(args[0], args);

fprintf(stderr, "Exec failed.\n");

return 1;

} else {

printf("Parent process - PID: %d\n", getpid());

wait(&status);

if (WIFEXITED(status)) {

printf("Child process exited with status: %d\n", WEXITSTATUS(status));

} else {

printf("Child process exited abnormally.\n");

printf("Parent process exiting.\n");

return 0;

Output

16
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY

Lab-2
Laboratory Objective: To implement Basic system calls of UNIX Operating
System
Learning Outcome: Familiarity with the use of basic calls of UNIX

Course Outcome: CO2


Blooms Taxonomy: BT1, BT2, BT3
Write programs using the following system calls of UNIX operating system
6. closedir()

7. Opendir()

4. readdir()

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <directory_path>\n", argv[0]);
return 1;
}
DIR *dir;
struct dirent *entry;
dir = opendir(argv[1]);

17
if (dir == NULL) {
perror("opendir");
return 1;
}
printf("Contents of directory '%s':\n", argv[1]);
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
Output

Lab – 3
Write programs using the I/O system calls of UNIX operating System

1. Open()
18
The open() function in C is used to open the file for reading, writing, or both. It is also
capable of creating the file if it does not exist. It is defined inside <unistd.h> header file
and the flags that are passed as arguments are defined inside <fcntl.h> header file.
Syntax of Open()
int open (const char* Path, int flags);

Parameters
 Path: Path to the file which we want to open.
 Use the absolute path beginning with “/” when you are not working in
the same directory as the C source file.
 Use relative path which is only the file name with extension, when you
are working in the same directory as the C source file.
 flags: It is used to specify how you want to open the file.

Program
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
extern int errno;
int main(){
int fd = open("foo.txt", O_RDONLY | O_CREAT);
printf("fd = %d\n", fd);
if (fd == -1) {
printf("Error Number % d\n", errno);
perror("Program");
}
return 0;
}
Output

19
2. read()
From the file indicated by the file descriptor fd, the read() function reads the
specified amount of bytes cnt of input into the memory area indicated by buf. A
successful read() updates the access time for the file. The read() function is also
defined inside the <unistd.h> header file.
Syntax of read() in C
size_t read (int fd, void* buf, size_t cnt);
Parameters
fd: file descriptor of the file from which data is to be read.
buf: buffer to read data from
cnt: length of the buffer
Return Value
return Number of bytes read on success
return 0 on reaching the end of file
return -1 on error
return -1 on signal interrupt
Important Points
 buf needs to point to a valid memory location with a length not smaller than
the specified size because of overflow.
 fd should be a valid file descriptor returned from open() to perform the read
operation because if fd is NULL then the read should generate an error.
 cnt is the requested number of bytes read, while the return value is the
actual number of bytes read. Also, some times read system call should read
fewer bytes than cnt.
Example of read() in C

Program
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main(){
int fd, sz;
char* c = (char*)calloc(100, sizeof(char));
20
fd = open("foo.txt", O_RDONLY);
if (fd < 0) {
perror("r1");
exit(1);
}
sz = read(fd, c, 10);
printf("called read(% d, c, 10). returned that"
" %d bytes were read.\n",
fd, sz);
c[sz] = '\0';
printf("Those bytes are as follows: % s\n", c);
return 0;
}
Output

3. write()
Writes cnt bytes from buf to the file or socket associated with fd. cnt should not be
greater than INT_MAX (defined in the limits.h header file). If cnt is zero, write()
simply returns 0 without attempting any other action.
The write() is also defined inside <unistd.h> header file.
Syntax of write() in C
size_t write (int fd, void* buf, size_t cnt);
Parameters
 fd: file descriptor
 buf: buffer to write data from.
 cnt: length of the buffer.
Return Value
 returns the number of bytes written on success.
 return 0 on reaching the End of File.
 return -1 on error.
 return -1 on signal interrupts.
21
Important Points about C write
 The file needs to be opened for write operations
 buf needs to be at least as long as specified by cnt because if buf size is less
than the cnt then buf will lead to the overflow condition.
 cnt is the requested number of bytes to write, while the return value is the
actual number of bytes written. This happens when fd has a less number of
bytes to write than cnt.
 If write() is interrupted by a signal, the effect is one of the following:
 If write() has not written any data yet, it returns -1 and sets errno to EINTR.
 If write() has successfully written some data, it returns the number of bytes it
wrote before it was interrupted.
Program
#include<stdio.h>
#include <fcntl.h>
main() {
int sz;
int fd = open("foo.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0)
{
perror("r1");
exit(1);
}
sz = write(fd, "hello geeks\n", strlen("hello geeks\n"));
printf("called write(% d, \"hello geeks\\n\", %d)."
" It returned %d\n", fd, strlen("hello geeks\n"), sz);
close(fd);
}
Output

4. Stat()
22
 Prototype: int stat(const char *path, struct stat *buf);
 Purpose: Retrieves metadata about a file or directory specified by
the path argument. The information is stored in the buf pointer, which typically
points to a struct stat structure.
 Return value: Returns 0 on success, -1 on failure.
Key Fields in struct stat:
 st_mode: File type and permissions (e.g., regular file, directory, symbolic link).
 st_size: File size in bytes.
 st_mtime: Time of last modification in seconds since the epoch.
 st_atime: Time of last access in seconds since the epoch.
 st_ctime: Time of last status change in seconds since the epoch.
 st_uid: User ID of the file's owner.
 st_gid: Group ID of the file's group.
 st_nlink: Number of hard links to the file.
 st_blksize: Optimal block size for I/O operations.

Program
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
return 1;
}
struct stat fileStat;
if (stat(argv[1], &fileStat) == -1) {
perror("stat");
return 1;
}
printf("File: %s\n", argv[1]);
printf("Size: %ld bytes\n", fileStat.st_size);
printf("Permissions: %o\n", fileStat.st_mode & 0777);
return 0;

23
}
5. Close()
Writes cnt bytes from buf to the file or socket associated with fd. cnt should not
be greater than INT_MAX (defined in the limits.h header file). If cnt is zero,
write() simply returns 0 without attempting any other action.
The write() is also defined inside <unistd.h> header file.
Syntax of write() in C

size_t write (int fd, void* buf, size_t cnt);

Parameters
 fd: file descriptor
 buf: buffer to write data from.
 cnt: length of the buffer.
Return Value
 returns the number of bytes written on success.
 return 0 on reaching the End of File.
 return -1 on error.
 return -1 on signal interrupts.
Important Points about C write
 The file needs to be opened for write operations
 buf needs to be at least as long as specified by cnt because if buf size is less
than the cnt then buf will lead to the overflow condition.
 cnt is the requested number of bytes to write, while the return value is the
actual number of bytes written. This happens when fd has a less number of
bytes to write than cnt.
 If write() is interrupted by a signal, the effect is one of the following:
 If write() has not written any data yet, it returns -1 and sets errno to
EINTR.
 If write() has successfully written some data, it returns the number of
bytes it wrote before it was interrupted.
Program
#include<stdio.h>
#include <fcntl.h>
main()
24
{
int sz;
int fd = open("foo.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0)
{
perror("r1");
exit(1);
}
sz = write(fd, "hello geeks\n", strlen("hello geeks\n"));

printf("called write(% d, \"hello geeks\\n\", %d)."


" It returned %d\n", fd, strlen("hello geeks\n"), sz);
close(fd);
}
Output

Lab 4
1. Given the list of processes, their CPU burst times and arrival times.
Print the gantt chart for FCFS and SJF. For each of the Scheduling
policies compute and print the average waiting and average
turnaround time.

a) FCFS(Non-preemtive Scheduling Algorithm)


#include <stdio.h>
25
typedef struct {
int process_id;
int arrival_time;
int burst_time;
} Process;
void calculateAvgTimes(Process processes[], int n) {
int total_waiting_time = 0, total_turnaround_time = 0;
int waiting_time = 0, turnaround_time = 0;

for (int i = 0; i < n; i++) {


turnaround_time += processes[i].burst_time;
total_turnaround_time += turnaround_time -
processes[i].arrival_time;
waiting_time += turnaround_time - processes[i].arrival_time -
processes[i].burst_time;
total_waiting_time += waiting_time;
}

float avg_waiting_time = (float)total_waiting_time / n;


float avg_turnaround_time = (float)total_turnaround_time / n;

printf("Average Waiting Time: %.2f\n", avg_waiting_time);


printf("Average Turnaround Time: %.2f\n",
avg_turnaround_time);
}

void FCFS(Process processes[], int n) {


int current_time = 0;

printf("Gantt Chart:\n");
for (int i = 0; i < n; i++) {
printf("| P%d ", processes[i].process_id);
26
current_time += processes[i].burst_time;
}
printf("|\n");

calculateAvgTimes(processes, n);
}

int main() {
// Sample processes
Process processes[] = {
{1, 0, 5},
{2, 1, 3},
{3, 2, 8},
{4, 3, 6}
};
int n = sizeof(processes) / sizeof(processes[0]);

FCFS(processes, n);

return 0;
}

Output

b) SJF(Non-Preemtive Scheduling Algorithm)


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define z 1000000007

27
#define sh 100000
#define pb push_back
#define pr(x) printf("%d ", x)

struct util {
int id;
int at;
int bt;
int ct;
int tat;
int wt;
}
ar[sh + 1];

struct util1 {

int p_id;
int bt1;
};

util1 range;

util1 tr[4 * sh + 5];

int mp[sh + 1];


bool cmp(util a, util b)
{
if (a.at == b.at)
return a.id < b.id;
return a.at < b.at;
}
28
void update(int node, int st, int end,
int ind, int id1, int b_t)
{
if (st == end) {
tr[node].p_id = id1;
tr[node].bt1 = b_t;
return;
}
int mid = (st + end) / 2;
if (ind <= mid)
update(2 * node, st, mid, ind, id1, b_t);
else
update(2 * node + 1, mid + 1, end, ind, id1, b_t);
if (tr[2 * node].bt1 < tr[2 * node + 1].bt1) {
tr[node].bt1 = tr[2 * node].bt1;
tr[node].p_id = tr[2 * node].p_id;
}
else {
tr[node].bt1 = tr[2 * node + 1].bt1;
tr[node].p_id = tr[2 * node + 1].p_id;
}
}

util1 query(int node, int st, int end, int lt, int rt)
{
if (end < lt || st > rt)
return range;
if (st >= lt && end <= rt)
return tr[node];
int mid = (st + end) / 2;
29
util1 lm = query(2 * node, st, mid, lt, rt);
util1 rm = query(2 * node + 1, mid + 1, end, lt, rt);
if (lm.bt1 < rm.bt1)
return lm;
return rm;
}

void non_preemptive_sjf(int n)
{

int counter = n;

int upper_range = 0;

int tm = min(INT_MAX, ar[upper_range + 1].at);

while (counter) {
for (; upper_range <= n;) {
upper_range++;
if (ar[upper_range].at > tm || upper_range > n) {
upper_range--;
break;
}

update(1, 1, n, upper_range,
ar[upper_range].id, ar[upper_range].bt);
}

util1 res = query(1, 1, n, 1, upper_range);


if (res.bt1 != INT_MAX) {
counter--;
30
int index = mp[res.p_id];
tm += (res.bt1);

ar[index].ct = tm;
ar[index].tat = ar[index].ct - ar[index].at;
ar[index].wt = ar[index].tat - ar[index].bt;

update(1, 1, n, index, INT_MAX, INT_MAX);


}
else {
tm = ar[upper_range + 1].at;
}
}
}

void execute(int n)
{
sort(ar + 1, ar + n + 1, cmp);
for (int i = 1; i <= n; i++)
mp[ar[i].id] = i;

non_preemptive_sjf(n);
}

void print(int n)
{

cout << "ProcessId "


<< "Arrival Time "
<< "Burst Time "
<< "Completion Time "
31
<< "Turn Around Time "
<< "Waiting Time\n";
for (int i = 1; i <= n; i++) {
cout << ar[i].id << " \t\t "
<< ar[i].at << " \t\t "
<< ar[i].bt << " \t\t "
<< ar[i].ct << " \t\t "
<< ar[i].tat << " \t\t "
<< ar[i].wt << " \n";
}
}

int main()
{
int n = 5;

range.p_id = INT_MAX;
range.bt1 = INT_MAX;

for (int i = 1; i <= 4 * sh + 1; i++) {


tr[i].p_id = INT_MAX;
tr[i].bt1 = INT_MAX;
}

ar[1].at = 1;
ar[1].bt = 7;
ar[1].id = 1;

ar[2].at = 2;
ar[2].bt = 5;
ar[2].id = 2;
32
ar[3].at = 3;
ar[3].bt = 1;
ar[3].id = 3;

ar[4].at = 4;
ar[4].bt = 2;
ar[4].id = 4;

ar[5].at = 5;
ar[5].bt = 8;
ar[5].id = 5;

execute(n);

print(n);
}
Output

Lab 5
1. Given the list of processes, their CPU burst times and arrival
time. Display/Print the gantt chart for SJF. For Each of the
33
scheduling Policies compute and print the average waiting time
and average turnaround time.

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define z 1000000007
#define sh 100000
#define pb push_back
#define pr(x) printf("%d ", x)

struct util {
int id;
int at;
int bt;
int ct;
int tat;
int wt;
}
ar[sh + 1];

struct util1 {

int p_id;
int bt1;
};

util1 range;
34
util1 tr[4 * sh + 5];

int mp[sh + 1];


bool cmp(util a, util b)
{
if (a.at == b.at)
return a.id < b.id;
return a.at < b.at;
}

void update(int node, int st, int end,


int ind, int id1, int b_t)
{
if (st == end) {
tr[node].p_id = id1;
tr[node].bt1 = b_t;
return;
}
int mid = (st + end) / 2;
if (ind <= mid)
update(2 * node, st, mid, ind, id1, b_t);
else
update(2 * node + 1, mid + 1, end, ind, id1, b_t);
if (tr[2 * node].bt1 < tr[2 * node + 1].bt1) {
tr[node].bt1 = tr[2 * node].bt1;
tr[node].p_id = tr[2 * node].p_id;
}
35
else {
tr[node].bt1 = tr[2 * node + 1].bt1;
tr[node].p_id = tr[2 * node + 1].p_id;
}
}

util1 query(int node, int st, int end, int lt, int rt)
{
if (end < lt || st > rt)
return range;
if (st >= lt && end <= rt)
return tr[node];
int mid = (st + end) / 2;
util1 lm = query(2 * node, st, mid, lt, rt);
util1 rm = query(2 * node + 1, mid + 1, end, lt, rt);
if (lm.bt1 < rm.bt1)
return lm;
return rm;
}

void non_preemptive_sjf(int n)
{

int counter = n;

int upper_range = 0;

int tm = min(INT_MAX, ar[upper_range + 1].at);


36
while (counter) {
for (; upper_range <= n;) {
upper_range++;
if (ar[upper_range].at > tm || upper_range > n) {
upper_range--;
break;
}

update(1, 1, n, upper_range,
ar[upper_range].id, ar[upper_range].bt);
}

util1 res = query(1, 1, n, 1, upper_range);


if (res.bt1 != INT_MAX) {
counter--;
int index = mp[res.p_id];
tm += (res.bt1);

ar[index].ct = tm;
ar[index].tat = ar[index].ct - ar[index].at;
ar[index].wt = ar[index].tat - ar[index].bt;

update(1, 1, n, index, INT_MAX, INT_MAX);


}
else {
tm = ar[upper_range + 1].at;
}
37
}
}

void execute(int n)
{
sort(ar + 1, ar + n + 1, cmp);
for (int i = 1; i <= n; i++)
mp[ar[i].id] = i;

non_preemptive_sjf(n);
}

void print(int n)
{

cout << "ProcessId "


<< "Arrival Time "
<< "Burst Time "
<< "Completion Time "
<< "Turn Around Time "
<< "Waiting Time\n";
for (int i = 1; i <= n; i++) {
cout << ar[i].id << " \t\t "
<< ar[i].at << " \t\t "
<< ar[i].bt << " \t\t "
<< ar[i].ct << " \t\t "
<< ar[i].tat << " \t\t "
<< ar[i].wt << " \n";
38
}
}

int main()
{
int n = 5;

range.p_id = INT_MAX;
range.bt1 = INT_MAX;

for (int i = 1; i <= 4 * sh + 1; i++) {


tr[i].p_id = INT_MAX;
tr[i].bt1 = INT_MAX;
}

ar[1].at = 1;
ar[1].bt = 7;
ar[1].id = 1;

ar[2].at = 2;
ar[2].bt = 5;
ar[2].id = 2;

ar[3].at = 3;
ar[3].bt = 1;
ar[3].id = 3;

ar[4].at = 4;
39
ar[4].bt = 2;
ar[4].id = 4;

ar[5].at = 5;
ar[5].bt = 8;
ar[5].id = 5;

execute(n);

print(n);
}
Output

40
Lab 6
1. Given the list of processes, their CPU burst times and arrival
time. Display/Print the gantt chart for Prirority CPU Scheduling.
For Each of the scheduling Policies compute and print the
average waiting time and average turnaround time.

#include <bits/stdc++.h>
using namespace std;

struct Process {
int pid;
int bt;
int priority;
};

bool comparison(Process a, Process b)


41
{
return (a.priority > b.priority);
}
void findWaitingTime(Process proc[], int n, int wt[])
{
wt[0] = 0;
for (int i = 1; i < n; i++)
wt[i] = proc[i - 1].bt + wt[i - 1];
}
void findTurnAroundTime(Process proc[], int n, int wt[],
int tat[])
{
for (int i = 0; i < n; i++)
tat[i] = proc[i].bt + wt[i];
}
void findavgTime(Process proc[], int n)
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;
findWaitingTime(proc, n, wt);
findTurnAroundTime(proc, n, wt, tat);
cout << "\nProcesses "
<< " Burst time "
<< " Waiting time "
<< " Turn around time\n";

for (int i = 0; i < n; i++) {


total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
42
cout << " " << proc[i].pid << "\t\t" << proc[i].bt
<< "\t " << wt[i] << "\t\t " << tat[i]
<< endl;
}

cout << "\nAverage waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}

void priorityScheduling(Process proc[], int n)


{
sort(proc, proc + n, comparison);
cout << "Order in which processes gets executed \n";
for (int i = 0; i < n; i++)
cout << proc[i].pid << " ";
findavgTime(proc, n);
}
int main() {
Process proc[]
= { { 1, 10, 2 }, { 2, 5, 0 }, { 3, 8, 1 } };
int n = sizeof proc / sizeof proc[0];
priorityScheduling(proc, n);
return 0;
}
OUTPUT

43
Lab 7
1. Given the list of processes, their CPU burst times and arrival
time. Display/Print the gantt chart for Round Robin CPU
Scheduling. For Each of the scheduling Policies compute and
print the average waiting time and average turnaround time.

#include<iostream>
using namespace std;
void findWaitingTime(int processes[], int n,
int bt[], int wt[], int quantum)
{
int rem_bt[n];
for (int i = 0 ; i < n ; i++)
rem_bt[i] = bt[i];

44
int t = 0;
while (1)
{
bool done = true;

for (int i = 0 ; i < n; i++)


{
if (rem_bt[i] > 0)
{
done = false;
if (rem_bt[i] > quantum)
{
t += quantum;
rem_bt[i] -= quantum;
}

else
{
t = t + rem_bt[i];
wt[i] = t - bt[i];
rem_bt[i] = 0;
}
}
}

if (done == true)
45
break;
}
}
void findTurnAroundTime(int processes[], int n,
int bt[], int wt[], int tat[])
{
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}

void findavgTime(int processes[], int n, int bt[], int quantum)


{
int wt[n], tat[n], total_wt = 0, total_tat = 0;

findWaitingTime(processes, n, bt, wt, quantum);

findTurnAroundTime(processes, n, bt, wt, tat);

cout << "PN\t "<< " \tBT "


<< " WT " << " \tTAT\n";

for (int i=0; i<n; i++)


{
total_wt = total_wt + wt[i];
46
total_tat = total_tat + tat[i];
cout << " " << i+1 << "\t\t" << bt[i] <<"\t "
<< wt[i] <<"\t\t " << tat[i] <<endl;
}

cout << "Average waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}
int main()
{
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];

int burst_time[] = {10, 5, 8};

int quantum = 2;
findavgTime(processes, n, burst_time, quantum);
return 0;
}
Output

47
LAB 8
1. Implement Memory Management Schemes FIRST FIT
#include <stdio.h>
#define MAX_BLOCKS 50

typedef struct {
int size; // Size of the block
int allocated; // Flag to indicate if the block is allocated (1) or free (0)
} MemoryBlock;
void initializeMemory(MemoryBlock memory[], int n) {
for (int i = 0; i < n; i++) {
48
memory[i].size = 0;
memory[i].allocated = 0;
}
}
void displayMemory(MemoryBlock memory[], int n) {
printf("Memory Status:\n");
for (int i = 0; i < n; i++) {
printf("Block %d - Size: %d, Allocated: %s\n", i+1, memory[i].size,
memory[i].allocated ? "Yes" : "No");
}
printf("\n");

int allocateMemoryFirstFit(MemoryBlock memory[], int n, int processSize) {


for (int i = 0; i < n; i++) {
if (!memory[i].allocated && memory[i].size >= processSize) {
memory[i].allocated = 1;
return i;
}
}
return -1; // Memory allocation failed
}

int main() {
MemoryBlock memory[MAX_BLOCKS];
int n, processSize;

49
printf("Enter the number of memory blocks: ");
scanf("%d", &n);
initializeMemory(memory, n);
for (int i = 0; i < n; i++) {
printf("Enter the size of block %d: ", i+1);
scanf("%d", &memory[i].size);
}
displayMemory(memory, n);
printf("Enter the size of the process: ");
scanf("%d", &processSize);
int allocatedBlockIndex = allocateMemoryFirstFit(memory, n, processSize);
if (allocatedBlockIndex != -1) {
printf("Memory allocated successfully to process. Allocated block: %d\n",
allocatedBlockIndex + 1);
} else {
printf("Memory allocation failed. No suitable block found.\n");
}
displayMemory(memory, n);

return 0;
}

50
LAB 9

1. Implement Memory Management Schemes BEST FIT

#include <stdio.h>
#define MAX_BLOCKS 50
51
typedef struct {
int size;
int allocated;
} MemoryBlock;
void initializeMemory(MemoryBlock memory[], int n) {
for (int i = 0; i < n; i++) {
memory[i].size = 0;
memory[i].allocated = 0;
}
}
void displayMemory(MemoryBlock memory[], int n) {
printf("Memory Status:\n");
for (int i = 0; i < n; i++) {
printf("Block %d - Size: %d, Allocated: %s\n", i+1, memory[i].size,
memory[i].allocated ? "Yes" : "No");
}
printf("\n");
}

int allocateMemoryBestFit(MemoryBlock memory[], int n, int processSize) {

int bestFitIndex = -1;

int minFragmentation = __INT_MAX__;

for (int i = 0; i < n; i++) {

if (!memory[i].allocated && memory[i].size >= processSize) {

int fragmentation = memory[i].size - processSize;

if (fragmentation < minFragmentation) {

minFragmentation = fragmentation;

bestFitIndex = i;
52
}

if (bestFitIndex != -1) {

memory[bestFitIndex].allocated = 1;

return bestFitIndex;

int main() {
MemoryBlock memory[MAX_BLOCKS];
int n, processSize;
printf("Enter the number of memory blocks: ");
scanf("%d", &n);
initializeMemory(memory, n);
for (int i = 0; i < n; i++) {
printf("Enter the size of block %d: ", i+1);
scanf("%d", &memory[i].size);
}
displayMemory(memory, n);

printf("Enter the size of the process: ");


scanf("%d", &processSize);
int allocatedBlockIndex = allocateMemoryBestFit(memory, n, processSize);
if (allocatedBlockIndex != -1) {
printf("Memory allocated successfully to process. Allocated block: %d\n",
allocatedBlockIndex + 1);
} else {
53
printf("Memory allocation failed. No suitable block found.\n");
}
displayMemory(memory, n);

return 0;
}

LAB 10

1. Implement Memory Management Schemes WORST FIT

#include <stdio.h>

#define MAX_BLOCKS 50
typedef struct {
54
int size;
int allocated;
} MemoryBlock;
void initializeMemory(MemoryBlock memory[], int n) {
for (int i = 0; i < n; i++) {
memory[i].size = 0;
memory[i].allocated = 0;
}
}
void displayMemory(MemoryBlock memory[], int n) {
printf("Memory Status:\n");
for (int i = 0; i < n; i++) {
printf("Block %d - Size: %d, Allocated: %s\n", i + 1, memory[i].size,
memory[i].allocated ? "Yes" : "No");
}

printf("\n");

int allocateMemoryWorstFit(MemoryBlock memory[], int n, int processSize) {

int worstFitIndex = -1;

int maxFragmentation = -1;


for (int i = 0; i < n; i++) {
if (!memory[i].allocated && memory[i].size >= processSize) {
int fragmentation = memory[i].size - processSize;
if (fragmentation > maxFragmentation) {
maxFragmentation = fragmentation;
worstFitIndex = i;
}
}

55
}
if (worstFitIndex != -1) {
memory[worstFitIndex].allocated = 1;
}

return worstFitIndex;
}
int main() {
MemoryBlock memory[MAX_BLOCKS];
int n, processSize;

printf("Enter the number of memory blocks: ");

scanf("%d", &n);

initializeMemory(memory, n);

for (int i = 0; i < n; i++) {

printf("Enter the size of block %d: ", i + 1);

scanf("%d", &memory[i].size);

displayMemory(memory, n);

printf("Enter the size of the process: ");


scanf("%d", &processSize);
int allocatedBlockIndex = allocateMemoryWorstFit(memory, n, processSize);
if (allocatedBlockIndex != -1) {
printf("Memory allocated successfully to process. Allocated block: %d\n",
allocatedBlockIndex + 1);
} else {
printf("Memory allocation failed. No suitable block found.\n");
}
56
displayMemory(memory, n);

return 0;
}

LAB 11

1. Implement FCFS Disk Scheuling Algorithm.

#include <stdio.h>
#include <stdlib.h>
int main() {
int n, head, i, seek_time = 0;
printf("Enter the number of disk requests: ");
scanf("%d", &n);

int requests[n];

57
printf("Enter the requests sequence: ");
for (i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}

printf("Enter the initial position of the head: ");


scanf("%d", &head);

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


seek_time += abs(head - requests[i]);

printf("Move from %d to %d\n", head, requests[i]);

head = requests[i];

printf("Total seek time: %d\n", seek_time);

return 0;

58
LAB-12
1. Implement SSTF Disk Scheuling technique.

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int findNearestTrack(int tracks[], int n, int head) {


int min_distance = INT_MAX;
int index = -1;
for (int i = 0; i < n; i++) {
59
if (!tracks[i]) continue; // Skip if track already visited

int distance = abs(tracks[i] - head);


if (distance < min_distance) {
min_distance = distance;
index = i;
}
}
return index;
}

int main() {

int n, head, i, seek_time = 0;

printf("Enter the number of disk requests: ");

scanf("%d", &n);

int requests[n];

printf("Enter the requests sequence: ");


for (i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}
printf("Enter the initial position of the head: ");
scanf("%d", &head);
int *visited = (int *)calloc(n, sizeof(int));
for (i = 0; i < n; i++) {
int nearest_index = findNearestTrack(requests, n, head);
visited[nearest_index] = 1;
seek_time += abs(head - requests[nearest_index]);

60
printf("Move from %d to %d\n", head, requests[nearest_index]);
head = requests[nearest_index];
}
printf("Total seek time: %d\n", seek_time);
free(visited);
return 0;

LAB-13
1. Implement SCAN Disk Scheuling technique.

#include <stdio.h>
#include <stdlib.h>
void sort(int arr[], int n) {
int temp;

61
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
int findFirstLargerTrack(int tracks[], int n, int head) {
for (int i = 0; i < n; i++) {
if (tracks[i] >= head) {
return i;
}

return -1; // No track found larger than head


}
int findLastSmallerTrack(int tracks[], int n, int head) {
for (int i = n - 1; i >= 0; i--) {
if (tracks[i] <= head) {
return i;
}
}
return -1; // No track found smaller than head
}

62
int main() {
int n, head, i, seek_time = 0;

printf("Enter the number of disk requests: ");


scanf("%d", &n);

int requests[n];

printf("Enter the requests sequence: ");


for (i = 0; i < n; i++) {
scanf("%d", &requests[i]);

printf("Enter the initial position of the head: ");

scanf("%d", &head);

sort(requests, n);

int start_index = findFirstLargerTrack(requests, n, head);

int end_index = findLastSmallerTrack(requests, n, head);

printf("Move from %d to %d\n", head, requests[start_index]);

seek_time += abs(head - requests[start_index]);

for (i = start_index + 1; i < n; i++) {

printf("Move from %d to %d\n", requests[i - 1], requests[i]);

seek_time += abs(requests[i] - requests[i - 1]);

for (i = end_index; i >= 0; i--) {

63
printf("Move from %d to %d\n", requests[i + 1], requests[i]);

seek_time += abs(requests[i] - requests[i + 1]);

printf("Total seek time: %d\n", seek_time);

return 0;

LAB-14
1. Implement LOOK Disk Scheuling Technique.

#include <stdio.h>
#include <stdlib.h>
void sort(int arr[], int n) {
int temp;
64
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
int findFirstLargerTrack(int tracks[], int n, int head) {
for (int i = 0; i < n; i++) {
if (tracks[i] >= head) {
return i;
}
}

return -1; // No track found larger than head

}
int findLastSmallerTrack(int tracks[], int n, int head) {
for (int i = n - 1; i >= 0; i--) {
if (tracks[i] <= head) {
return i;
}
}
return -1; // No track found smaller than head
65
}

int main() {
int n, head, i, seek_time = 0;
printf("Enter the number of disk requests: ");
scanf("%d", &n);
int requests[n];
printf("Enter the requests sequence: ");
for (i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}

printf("Enter the initial position of the head: ");

scanf("%d", &head);

sort(requests, n);

int start_index = findFirstLargerTrack(requests, n, head);

int end_index = findLastSmallerTrack(requests, n, head);

if (start_index != -1 && end_index != -1) {


printf("Move from %d to %d\n", head, requests[start_index]);
seek_time += abs(head - requests[start_index]);
for (i = start_index + 1; i < n; i++) {
printf("Move from %d to %d\n", requests[i - 1], requests[i]);
seek_time += abs(requests[i] - requests[i - 1]);
}
for (i = end_index; i >= 0; i--) {
66
printf("Move from %d to %d\n", requests[i + 1], requests[i]);
seek_time += abs(requests[i] - requests[i + 1]);
}
} else {
printf("No requests to process.\n");
}

printf("Total seek time: %d\n", seek_time);

return 0;
}

67

You might also like