0% found this document useful (0 votes)
9 views37 pages

C Programs for CPU Scheduling Algorithms

The document outlines various CPU scheduling algorithms implemented in C programming, including Shortest Job First (SJF), First Come First Served (FCFS), Round Robin, Priority Scheduling, and the Reader-Writer problem using semaphores. Each section provides an aim, algorithm steps, and corresponding C code for implementation. Additionally, it includes the Banker's algorithm for deadlock avoidance, detailing the steps to ensure system safety.

Uploaded by

skamalraj2023
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views37 pages

C Programs for CPU Scheduling Algorithms

The document outlines various CPU scheduling algorithms implemented in C programming, including Shortest Job First (SJF), First Come First Served (FCFS), Round Robin, Priority Scheduling, and the Reader-Writer problem using semaphores. Each section provides an aim, algorithm steps, and corresponding C code for implementation. Additionally, it includes the Banker's algorithm for deadlock avoidance, detailing the steps to ensure system safety.

Uploaded by

skamalraj2023
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

[Link]: 1.

SHORTEST JOB FIRST(SJF) SCHEDULING


ALGORITHM
AIM:
To write a C program for Shortest Job First scheduling algorithm.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the number of processes n.
Step 3: For each process i from 0 to n - 1: Assign a name like P1, P2, etc.
Step 4: Sort the processes in ascending order based on burst time using bubble
sort:
Step 5: Calculate Waiting Time and Turnaround Time by WT[0] = 0 and Set
TAT[0] = BT[0].
Step 6: Print process name, burst time, waiting time, turnaround time for all
processes.
Step 7: Calculate:
Total_WT = sum of all WT[i]
Total_TAT = sum of all TAT[i]
Average_WT = Total_WT / n
Average_TAT = Total_TAT / n
Step 8: Display Average_WT and Average_TAT.
Step 9: End the program.
CODING:
#include <stdio.h>
#include <string.h>
#include<conio.h>
int main()
{
char s[21][21],chng[20];
int wt[21], a[21], n,i, j, temp, tr[21];
float tot = 0.0, at = 0.0;
clrscr();
printf("\nShortest Job First Algorithm");
printf("\nEnter the number of processes: ");
scanf("%d", &n);
printf("Enter Burst Time for each process\n");
for (i= 0;i< n;i++)
{
sprintf(s[i], "P%d",i+ 1);
printf("%s: ", s[i]);
scanf("%d", &a[i]);
}
for (i= 0;i< n - 1;i++)
{
for (j =i+ 1; j < n;j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
strcpy(chng, s[i]);
strcpy(s[i], s[j]);
strcpy(s[j],chng);
}
}
}
wt[0] = 0;
tr[0] = a[0];
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaroundTime");
printf("\n..................................................\n");
for (i= 0;i< n;i++)
{if (i>0)
{
wt[i] =wt[i- 1] + a[i- 1];
tr[i]=wt[i] + a[i];
}
printf("%s\t%d\t\t%d\t\t%d\n", s[i], a[i],wt[i], tr[i]);
tot+=wt[i];
at += tr[i];
}
printf("\nAverage Waiting Time = %.2f\n", tot / n);
printf("Average Turnaround Time = %.2f\n", at / n);
getch();
return 0;
}

OUTPUT :
[Link]: 2. FRIST COME FIRST SERVED ALGORITHM
AIM:
To write a C program for First Come First Served algorithm
ALGORITHM:
Step 1: Start the program.
Step 2: Read the number of processes n.
Step 3: For each process i from 0 to n - 1: Assign a name like P1, P2
Step 4: Initialize the waiting time (wt) for the first process to 0.
Step 5: Calculate the waiting time for each remaining process (i from 1 to n-1)
Step 6: compute turnaround time (tatfor each process.
Tat[i]=bt[i]+wt[i]
Step 7: Display the burst time ,waiting time, and turnaround time for each
process.
Step 7: Calculate the average waiting time and average turnaround time by
using avwt /n , avtat /n respectively.
Step 8: Display Average_WT and Average_TAT.
Step 9: End the program.
CODING:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
clrscr();
printf("\n Frist come first served Algorithm");
printf("\n***********************************");
printf("\n Enter the number of process:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("p%d:",i+1);
scanf("%d",&bt[i]);
}
wt[0]=0;
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
}
printf("\n.......................................");
printf("\n process burst time waiting time turnaround time");
printf("\n.......................................");
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];
avwt+=wt[i];
avtat+=tat[i];
printf("\n p%d\t%d\t\t%d\t%d",i+1,bt[i],wt[i],tat[i]);
}
printf("\n........................................");
printf("\n Average waiting time:%d",avwt/n);
printf("\n Average turnaround time:%d",avtat/n);
getch();
}
OUTPUT :
[Link]: 3. ROUND ROBIN

AIM :
To write a C program for Round Robin.
ALGORITHM :
Step 1: Start the program.
Step 2: Input number of processes n.
Step 3: For each process i (0 to n-1):
Input Arrival Time at[i]
Input Burst Time bt[i]
Set Remaining Time rt[i] = bt[i]
Step 4: Input Time Quantum tq.
Step 5: Initialize:
t = 0 → Current time
remain = n → Number of remaining processes
wt = 0 → Total waiting time
tat = 0 → Total turnaround time
flag = 0 → Used to check if a process just completed
cnt = 0 → Index to track current process
Step 6: While remain ≠ 0, repeat:
If rt[cnt] > 0 and at[cnt] ≤ t:
If rt[cnt] ≤ tq:
t = t + rt[cnt]
rt[cnt] = 0
Set flag = 1 (process completed)
Else:
rt[cnt] = rt[cnt] – tq
t = t + tq
If rt[cnt] == 0 and flag == 1:
Calculate Turnaround Time = t - at[cnt]
Calculate Waiting Time = Turnaround Time - bt[cnt]
Print these values
Update wt and tat
remain = remain – 1
Set flag = 0
Find the next process that has arrived (at[i] ≤ t) and has rt[i] > 0.
If found, update cnt to that index.
Else, increment t (CPU idle).
Step 7: After loop ends, calculate:
Average Waiting Time = wt / n
Average Turnaround Time = tat / n
Step 8: Display the average values.
Step 9: End the program.

CODING :
#include<stdio.h>
#include<conio.h>
int main()
{
int cnt,j,n,t,remain,flag=0,tq;
int wt=0,tat=0,at[10],bt[10],rt[10];
clrscr();
printf("Enter Total Process:\t ");
scanf("%d",&n);
remain=n;
for(cnt=0;cnt<n;cnt++)
{
printf("Enter Arrival Time and Burst Time for Process Process
Number %d :",cnt+1);
scanf("%d",&at[cnt]);
scanf("%d",&bt[cnt]);
rt[cnt]=bt[cnt];
}
printf("Enter Time Quantum:\t");
scanf("%d",&tq);
printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n");
for(t=0,cnt=0;remain!=0;)
{
if(rt[cnt]<=tq && rt[cnt]>0)
{
t+=rt[cnt];
rt[cnt]=0;
flag=1;
}
else if(rt[cnt]>0)
{
rt[cnt]-=tq;
t+=tq;
}
if(rt[cnt]==0 && flag==1)
{
remain--;
printf("P[%d]\t|\t%d\t|\t%d\n",cnt+1,t-at[cnt],t-at[cnt]-bt[cnt]);
wt+=t-at[cnt]-bt[cnt];
tat+=t-at[cnt];
flag=0;
}
if(cnt==n-1)
cnt=0;
else if(at[cnt+1]<=t)
cnt++;
else
cnt=0;
}
printf("\nAverage Waiting Time= %f\n",wt*1.0/n);
printf("Avg Turnaround Time = %f",tat*1.0/n);
getch();
return 0;
}

OUTPUT

Enter Total Process: 4


Enter Arrival Time and Burst Time for Process Process Number 1 :0 5
Enter Arrival Time and Burst Time for Process Process Number 2 :1 4
Enter Arrival Time and Burst Time for Process Process Number 3 :2 2
Enter Arrival Time and Burst Time for Process Process Number 4 :4 1
Enter Time Quantum: 2
Process |Turnaround Time|Waiting Time

P[3] | 4 | 2
P[4] | 3 | 2
P[2] | 10 | 6
P[1] | 12 | 7

Average Waiting Time= 4.250000


Avg Turnaround Time = 7.250000
[Link]: 4. PRIORITY SCHEDULING ALGORITHM

AIM :
To write a C program for Priority Scheduling Algorithm.
ALGORITHM :
Step 1: Start the program.
Step 2: Input process ID, burst time, and priority.
Step 3: Sort processes by increasing priority (i.e., highest priority first).
Step 4: Initialize WT[0] = 0, then:
WT[i] = WT[i-1] + BT[i-1]
TAT[i] = WT[i] + BT[i]
Step 5: Print Process ID, BT, WT, TAT, and priority.
Step 6: Calculate and display:
Average WT = sum(WT) / n
Average TAT = sum(TAT) / n
Step 7: Display the value
Step 8: stop the program.

CODING :
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[20][20],chng[20];
int wt[20],a[20],n,i,j,temp,trn[20],p[20];
float tot,t;
clrscr();
printf("\n priority scheduling algorithm");
printf("\n******************************");
printf("\n Enter the no of process:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter process id and burst time and priority \n");
scanf("%s%d%d",&s[i],&a[i],&p[i]);
}
wt[0]=0;
a[0]=0;
t=tot=0;
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(p[i]>p[j])
{
temp=a[i];a[i]=a[j];
a[j]=temp;
temp=p[i];
p[i]=p[j];
p[j]=temp;
strcpy(chng,s[i]);
strcpy(s[i],s[j]);
strcpy(s[j],chng);
}
}
}
printf("\n...................................");
printf("\n process burst time waiting time turnaround time priority");
printf("\n...................................");
for(i=1;i<=n;i++)
{
wt[i]=wt[i-1]+a[i-1];
trn[i]=wt[i]+a[i];
printf("\n%s\t%d\t\t%d\t\t%d\t%d",s[i],a[i],wt[i],trn[i],p[i]);
tot=tot+wt[i];
t=t+trn[i];
}
printf("\n....................................");
printf("\n Average waiting time=%6.2f",tot/n);
printf("\n Average turnaround time=%6.2f",t/n);
getch();
}

OUTPUT

priority scheduling algorithm


******************************
Enter the no of process:2
Enter process id and burst time and priority
p1 65 26
Enter process id and burst time and priority
p2 55 87

...............................................................
process burst time waiting time turnaround time priority
...............................................................
p1 65 0 65 26
p2 55 65 120 87
...............................................................
Average waiting time= 32.50
Average turnaround time= 92.50
5. IMPLEMENTATION OF READER -WRITER PROBLEM
USING SEMAPHORE
AIM :
To write a c program for implementation of Reader – Writer problem using
semaphore.

ALGORITHM :
Step 1: start the program.
Step 2: x=1  semaphore for controlling access to the critical section(writer).
Step 3: readcount=1  semaphore for protecting the rc counter.
Step 4: rc=0  Number of active readers.
Step 5: wait(readcount):Acquire access to modify rc.
Step 6: Increment rc: If this is the first reader,block writers by wait(x).
Step 7: Signal(readcount):Realease access to rc.
Step 8: Read the data.
Step 9: p1(&x);  wait for exclusive access.
Step 10: write to the data.
Step 11: v1(&x);  Release exclusive access.

CODING :
#include<stdio.h>
#include<conio.h>
int x=1,rc=0,readcount=1;
void p(int*a)
{
while(*a==0)
{
printf("Busy wait");
}
*a=*a-1;
}
void v(int*b)
{
*b=*b+1;
}
void p1(int*c)
{
while(*c==0)
{
printf("Busy wait");
}
*c=*c-1;
}
void v1(int*d)
{
*d=*d+1;
}
void reader()
{
int flag=1;
while(flag==1)
{
p(&readcount);
rc=rc+1;
if(rc==1)
p1(&x);
v(&readcount);
printf("\n Reader is reading");
p(&readcount);
rc=rc-1;
if(rc==0)
v1(&x);
v(&readcount);
flag=0;
}
}
void writer()
{
p1(&x);
printf("\n writer is writing");
v1(&x);
}
void main()
{
clrscr();
printf("\n Reader-writers problem");
printf("\n *************************\n");
reader();
writer();
reader();
writer();
getch();
}

OUTPUT :
[Link]: 6. BANKER’S ALGORITHM FOR DEADLOCK
AVOIDANCE

AIM:
To write a C program for Banker’s algorithm for deadlock avoidance.
ALGORITHM :
Step 1: start the program.
Step 2: Initialize System variables like allocationMatrix,maxMatrix,……
Step 3: Calculate the Need matrix
Step 4: Mark all processes as not finished using isFinished[]
Step 5: Start safeSequence search repeat the following loop up to
numProcesses times to try and find a safeSequence.
Step 6: Find an Executable Process for each process i,if is not finished,its need
is less than or equal.
Step 7: Simulate process execution(if the process is found)
add its allocated resources back to the available pool(simulate
resources release).
Mark the process as finished.
add the process to the safeSequence array.
Step 8: Repeat until all process are checked and check for safe state.
Step 9: Output the safeSequence,if not safe,Report unsafe state like,
(The system is not in a safe state)
CODING :
#include<stdio.h>
int main()
{
int i,j,k,y;
int numProcesses=5;
int numResources=3;
int allocationMatrix[5][3]={{0,1,0},{1,0,0},{2,0,2},{3,1,1},{4,0,2}};
int maxMatrix[5][3]={{7,5,3},{3,2,2},{9,0,2},{2,2,2},{4,3,3}};
int availableResources[3]={3,3,2};
int isFinished[5],safeSequence[3],index=0;
int needMatrix[5][3];
int flag=1;
clrscr();
for(k=0;k<numProcesses;k++)
{
isFinished[k]=0;
}
for(i=0;i<numProcesses;i++)
{
for(j=0;j<numResources;j++)
needMatrix[i][j]=maxMatrix[i][j]-allocationMatrix[i][j];
}
for(k=0;k<numProcesses;k++)
{
for(i=0;i<numProcesses;i++)
{
if(isFinished[i]==0)
{
int flag=0;
for(j=0;j<numResources;j++)
{
if(needMatrix[i][j]>availableResources[j])
{
flag=1;
break;
}
}
if(flag==0)
{
safeSequence[index++]=i;
for(y=0;y<numResources;y++)
availableResources[y]+=allocationMatrix[i][y];
isFinished[i]=1;
}
}
}
}
for(i=0;i<numProcesses;i++)
{
if(isFinished[i]==0)
{
flag=0;
printf("The system is no safe.\n");
break;
}
}
if(flag==1)
{
printf("safe Sequence:");
for(i=0;i<numProcesses-1;i++)
printf("P%d->",safeSequence[i]);
printf("P%d\n",safeSequence[numProcesses-1]);
}
getch();
return 0;
}
OUTPUT :
[Link]: 7. IMPLEMENTATION OF FIFO PAGE
REPLACEMENT ALGORITH
AIM:
To write a C program to implement of FIFO page replacement algorithm.
ALGORITHM:
Step 1: Start the program.
Step 2: Input the number of pages in the reference string (n).
Step 3: Input the page reference string (sequence of page numbers requested by
the process).
Step 4: Input the number of available page frames (no), i.e., how many pages
can be held in memory at once.
Step 5: Initialize all frame slots to empty (e.g., set each to -1 or another sentinel
value).
Step 6: Initialize variables:
count = 0 (to count page faults)
j = 0 (to track which fram e to replace next using FIFO)
Step 7: For each page in the reference string (loop through all pages):
 Check if the page is already in any frame (a page hit).
 If yes, do nothing (no page fault).
 If no, it’s a page fault:
Replace the page at the current j position (FIFO order).
Increment the j index (j = (j + 1) % no) to maintain circular FIFO order.
Increment the page fault count.
Step 8: After each page reference, display the current state of the frame (if
needed).
Step 9: Continue this process until all page references are processed.
Step 10: Output the total number of page faults.
Step 11: End the program.
CODING:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n,a[50],frame[10],no,k,avail,count=0;
clrscr();
printf("\n FIFO PAGE REPLACEMENT ALGORITHM");
printf("\n*********************************");
printf("\n Enter the number of pages:");
scanf("%d",&n);
printf("Enter the page number:");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the number of frames:");
scanf("%d",&no);
for(i=0;i<no;i++)
frame[i]=-1;
j=0;
printf("Ref string page frames\n");
for(i=1;i<=n;i++)
{
printf("%d\t\t",a[i]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if(avail==0)
{
frame[j]=a[i];
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("Page fault: %d",count);
getch();
}
OUTPUT:
[Link]: 8. LRU PAGE REPLACEMENT ALGORITHM
AIM:
To write a C program for LRU page replacement algorithm.
ALGORITHM:
Step 1: Start the program.
Step 2: Input the number of pages (n) in the reference string.
Step 3: Input the reference string (an array of page numbers).
Step 4: Input the number of frames (f) (number of pages that can be held in
memory at once).
Step 5: Initialize an empty frame list and a page fault counter to 0.
Step 6: For each page in the reference string:
 Check if the page is already in memory (frame).
 If yes, it is a page hit – update its "recently used" status.
 If no, it is a page fault:
 If there is space in memory, insert the page.
 If memory is full, remove the least recently used page and insert the new
one.
Step 7: Update usage history: Track which pages were recently accessed (e.g.,
using a counter, timestamp, or stack).
Step 8: Increment the page fault counter if a page was inserted.
Step 9: Display the current state of memory (optional, for visualization).
Step 10: Repeat step 6 for all pages in the reference string.
Step 11: Print the total number of page faults and end.
CODING:
#include<stdio.h>
void main()
{
int q[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20];
clrscr();
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);
getch();
}
OUTPUT:
[Link]: 9. IMPLEMENT FIRST FIT, BEST FIT, WORST FIT
ALGORITHM FOR MEMORY MANAGEMENT
AIM:
To write C program for implement First fit, Best fit, Worst fit algorithm for memory
management.
ALGORITHM:
Step 1: Input number of memory blocks (nb) and files (nf).
Step 2: Input the sizes of each memory block and store them in an array b[].
Step 3: Input the sizes of each file and store them in an array f[].
Step 4: Input the desired allocation method:
first – First Fit
Best – Best Fit
Worst – Worst Fit
Step 5: Initialize helper arrays:
bf[] to mark blocks as free (0) or used (1).
ff[] to store the index of the block each file is allocated to (default to -1).
Step 6: Loop through each file f[i]:
Set index = -1 (no block assigned yet).
Step 7: For each file, check each block b[j] to find a suitable one based on the chosen
method:
First Fit: Choose the first block that is large enough and free.
Best Fit: Choose the smallest suitable free block (least leftover space).
Worst Fit: Choose the largest suitable free block (most leftover space).
Step 8: If a suitable block is found (i.e., index != -1):
Assign block index to file i → ff[i] = index
Mark block as used → bf[index] = 1
Step 9: If no suitable block is found:
File i remains unallocated → ff[i] = -1
Step 10: After all allocations, display results:
For each file:
If allocated, show file number, size, block number, block size, and fragmentation.
If not allocated, indicate "Not Allocated".
Step 11: End of algorithm.

CODING :
#include <stdio.h>
#define max 25
void allocate(int b[], int f[], int nf, int nb, char* method);
int main()
{
int b[max], f[max], nb, nf, i;
char method[10];
printf("Enter the number of blocks: ");
scanf("%d", &nb);
printf("Enter the number of files: ");
scanf("%d", &nf);
printf("Enter the size of the blocks:\n");
for(i = 0; i < nb; i++)
{
printf("Block %d: ", i+1);
scanf("%d", &b[i]);
}
printf("Enter the size of the files:\n");
for(i = 0; i < nf; i++)
{
printf("File %d: ", i+1);
scanf("%d", &f[i]);
}
printf("Enter allocation method (worst, best, first): ");
scanf("%s", method);
allocate(b, f, nf, nb, method);
return 0;
}
void allocate(int b[], int f[], int nf, int nb, char* method)
{
int bf[max], ff[max];
int i, j, temp, highest, lowest, index;
for(i = 0; i < nf; i++)
{ ff[i] = -1;
}

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


{
bf[i] = 0;
}
for(i = 0; i < nf; i++)
{
index = -1;
if (strcmp(method, "worst") == 0)
{
highest = -1;
for(j = 0; j < nb; j++)
{
if(bf[j] == 0 && b[j] >= f[i])
{
temp = b[j] - f[i];
if(temp > highest)
{
highest = temp;
index = j;
}
}
}
}
else if (strcmp(method, "best") == 0)
{
lowest = max;
for(j = 0; j < nb; j++)
{
if(bf[j] == 0 && b[j] >= f[i])
{
temp = b[j] - f[i];
if(temp < lowest)
{
lowest = temp;
index = j;
}
}
}
}
else if (strcmp(method, "first") == 0)
{ for(j = 0; j < nb; j++)
{
if(bf[j] == 0 && b[j] >= f[i])
{
index = j;
break;
}
}
}
if(index != -1)
{
ff[i] = index; bf[index] = 1;
}
}

printf("\nFile_no\tFile_size\tBlock_no\tBlock_size\tFragment\n");
for(i = 0; i < nf; i++)
{
printf("%d\t\t%d\t\t", i+1, f[i]); if(ff[i] != -1)
{
printf("%d\t\t%d\t\t%d\n", ff[i]+1, b[ff[i]], b[ff[i]] - f[i]);
}
else
{
printf("Not Allocated\n");
}
}
}
OUTPUT:

You might also like