priority.c
74 linesc
DOWNLOAD
1// Aim: Program to perform Priority operations (Priority).
2#include<stdio.h>
3
4struct process {
5    int pid;
6    int bt;
7    int priority;
8    int wt;
9    int tat;
10};
11
12void sort(int n, struct process p[]) {
13    for (int i = 0; i < n; i++) {
14        for (int j = 0; j < n - i - 1; j++) {
15            if (p[j].priority > p[j + 1].priority) {
16                struct process temp = p[j];
17                p[j] = p[j + 1];
18                p[j + 1] = temp;
19            }
20        }
21    }
22}
23
24void findtime(int n, struct process p[]) {
25    p[0].wt = 0;
26    p[0].tat = p[0].bt;
27    for (int i = 1; i < n; i++) {
28        p[i].wt = p[i - 1].bt + p[i - 1].wt;
29        p[i].tat = p[i].bt + p[i].wt;
30    }
31}
32
33void ganttchart(int n, struct process p[]) {
34    printf("\nGantt Chart\n");
35    printf("-----------------\n");
36    for (int i = 0; i < n; i++) {
37        printf("| P%d ", p[i].pid);
38    }
39    printf("|\n");
40    for (int i = 0; i < n; i++) {
41        if(i == 0) {
42            printf("0   ", p[i].tat);
43        } printf("%d   ", p[i].tat);
44    }
45    printf("\n");
46}
47
48void main() {
49    printf("Enter the number of processes: ");
50    int n;
51    scanf("%d", &n);
52    struct process p[n];
53    for (int i = 0; i < n; i++) {
54        p[i].pid = i + 1;
55        printf("Enter the burst time of process %d: ", p[i].pid);
56        scanf("%d", &p[i].bt);
57        printf("Enter the priority of process %d: ", p[i].pid);
58        scanf("%d", &p[i].priority);
59    }
60    sort(n, p);
61    findtime(n, p);
62    ganttchart(n, p);
63
64    float avgwt = 0, avgtat = 0;
65    for(int i = 0; i < n; i++) {
66        avgwt += p[i].wt;
67        avgtat += p[i].tat;
68    }
69    avgwt /= n;
70    avgtat /= n;
71    printf("average waiting time = %f\n", avgwt);
72    printf("average turnaround time = %f\n", avgtat);
73}
74