# Implementation of LRU Page Replacement Algorithm in C++

Here is C++ implementation of LRU Algorithm.

```#include<iostream.h>

#include<conio.h>

void main() {
clrscr();
int fs, n;
cout << "\n Enter Framesize:";
cin >> fs;
cout << "\n Enter No of pages:";
cin >> n;
int d = fs + 2;
int cf[50][50];
int i, j, k, l, p, q, tc, z;
int temp[50];
cout << "\n Enter Pages";
for (i = 0; i < n; i++) {
cin >> cf[i][0];
}
for (i = 0; i < n; i++) {
for (j = 2; j < d; j++) {
cf[i][j] = -1;
}
}
for (i = 0; i < n; i++) {
if (i != 0) {
for (j = 2; j < d; j++) {
cf[i][j] = cf[i - 1][j];
}
}
p = 0;
for (j = 2; j < d; j++) {
if (cf[i][j] == cf[i][0])
p = 1;
}
if (p == 1) {
cf[i][1] = 1;
} else {
cf[i][1] = 0;
tc = 0;
for (l = 0; l < 50; l++) {
temp[l] = -1;
}
for (k = i; k >= 0; k--) {
p = 0;
for (l = 0; l < fs; l++) {
if (temp[l] == cf[k][0]) {
p = 1;
}
}
if (p == 0) {
temp[tc] = cf[k][0];
tc++;
}
}
q = temp[fs];
z = 0;
for (l = 2; l < d; l++) {
if ((cf[i][l] == q) && (z == 0)) {
cf[i][l] = cf[i][0];
z = 1;
}
}

}
}
int hc = 0;
int mc = 0;
cout << "\nPage\tHM\n";
for (i = 0; i < n; i++) {
for (j = 0; j < d; j++) {
cout << cf[i][j];
cout << "\t";
}
if (cf[i][1] == 0)
mc++;
if (cf[i][1] == 1)
hc++;
cout << "\n";
}
cout << "\n Hits:" << hc;
cout << "\n Miss:" << mc;
getch();
}

/* Output

Enter Framesize:3

Enter No of pages:20

Enter Pages7
0
1
2
0
3
0
4
2
3
0
3
2
1
2
0
1
7
0
1

Page    HM
7       0       7       -1      -1
0       0       7       0       -1
1       0       7       0       1
2       0       2       0       1
0       1       2       0       1
3       0       2       0       3
0       1       2       0       3
4       0       4       0       3
2       0       4       0       2
3       0       4       3       2
0       0       0       3       2
3       1       0       3       2
2       1       0       3       2
1       0       1       3       2
2       1       1       3       2
0       0       1       0       2
1       1       1       0       2
7       0       1       0       7
0       1       1       0       7
1       1       1       0       7

Hits:8
Miss:12
*/
```

This site uses Akismet to reduce spam. Learn how your comment data is processed.