0% found this document useful (0 votes)
2 views2 pages

Page Replacement C Code

The document contains a C program that implements three page replacement algorithms: FIFO, Optimal, and LRU. Each algorithm tracks page faults based on a given set of page references and a specified memory capacity. The program outputs the number of page faults for each algorithm when executed with a sample set of pages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Page Replacement C Code

The document contains a C program that implements three page replacement algorithms: FIFO, Optimal, and LRU. Each algorithm tracks page faults based on a given set of page references and a specified memory capacity. The program outputs the number of page faults for each algorithm when executed with a sample set of pages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#define MAX 50

void fifo(int pages[], int n, int capacity) {


int queue[MAX], front = 0, rear = 0, faults = 0, i, j, found;
for (i = 0; i < n; i++) {
found = 0;
for (j = front; j < rear; j++) {
if (queue[j] == pages[i]) {
found = 1;
break;
}
}
if (!found) {
if (rear - front == capacity) front++;
queue[rear++] = pages[i];
faults++;
}
}
printf("FIFO Page Faults: %d\n", faults);
}

void optimal(int pages[], int n, int capacity) {


int memory[MAX], faults = 0, i, j, k, index, farthest, found;
for (i = 0; i < n; i++) {
found = 0;
for (j = 0; j < capacity; j++) {
if (memory[j] == pages[i]) {
found = 1;
break;
}
}
if (!found) {
if (i < capacity) memory[i] = pages[i];
else {
farthest = i + 1;
index = -1;
for (j = 0; j < capacity; j++) {
for (k = i + 1; k < n; k++) {
if (memory[j] == pages[k]) {
if (k > farthest) {
farthest = k;
index = j;
}
break;
}
}
if (k == n) {
index = j;
break;
}
}
memory[index] = pages[i];
}
faults++;
}
}
printf("Optimal Page Faults: %d\n", faults);
}

void lru(int pages[], int n, int capacity) {


int memory[MAX], recent[MAX], faults = 0, i, j, k, found, lru_index;
for (i = 0; i < n; i++) {
found = 0;
for (j = 0; j < capacity; j++) {
if (memory[j] == pages[i]) {
found = 1;
recent[j] = i;
break;
}
}
if (!found) {
if (i < capacity) {
memory[i] = pages[i];
recent[i] = i;
} else {
lru_index = 0;
for (k = 1; k < capacity; k++) {
if (recent[k] < recent[lru_index]) lru_index = k;
}
memory[lru_index] = pages[i];
recent[lru_index] = i;
}
faults++;
}
}
printf("LRU Page Faults: %d\n", faults);
}

int main() {
int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
int n = sizeof(pages)/sizeof(pages[0]);
int capacity = 4;
fifo(pages, n, capacity);
optimal(pages, n, capacity);
lru(pages, n, capacity);
return 0;
}

You might also like