X
- Top Links
- PrepInsta Home
- OS Home
- Introduction
- CPU Scheduling
- What is Process?
- Process Lifecyle
- Process Control Block
- Process Scheduling
- Context Switching
- CPU Scheduling
- FCFS Scheduling
- SJF (non-preemptive)
- SJF (Preemptive - SRTF)
- Round Robin
- Priority Scheduling
- Convoy Effect
- Scheduler Vs Dispatcher
- Preemptive Vs non
- Preemptive scheduling
- Non preemptive scheduling
- Process Synchronization
- Deadlock
- Popular Algorithms
- Memory Management
- File System
- Others
- Youtube
- Whatsapp Group
- Telegram Group
- Contact us






Please login
Prime

Prepinsta Prime
Video courses for company/skill based Preparation
(Check all courses)
Get Prime Video
Prime

Prepinsta Prime
Purchase mock tests for company/skill building
(Check all mocks)
Get Prime mock
Optimal Page Replacement In C

Optimal Page Replacement
The process in an operating system occupies some dedicated memory. This memory is further divided into chunks called pages. These pages are brought from secondary memory to the primary memory as the CPU demands them. This method is known as page swapping and is done through an algorithm.
Optimal Page replacement program in C
#include<stdio.h> int main() { //variable declaration and initialization int frames_number, pages_number, frames[10], pages[30], temp[10], flag1, flag2, flag3, i, j, k, pos, max, miss = 0; //code to input the frame number printf("Enter number of frames: "); scanf("%d", & frames_number); //code to input number of pages printf("Enter number of pages: "); scanf("%d", &pages_number); //code to define reference string, page numbers, and frame numbers printf("Enter page reference string: "); for(i = 0; i < pages_number; ++i){ scanf("%d", &pages[i]); } for(i = 0; i < frames_number; ++i){ frames[i] = -1; } for(i = 0; i < pages_number; ++i){ flag1 = flag2 = 0; for(j = 0; j < frames_number; ++j){ if(frames[j] == pages[i]){ flag1 = flag2 = 1; break; } } //definition of the flag at the starting of the string if(flag1 == 0){ for(j = 0; j < frames_number; ++j){ if(frames[j] == -1){ faults++; frames[j] = pages[i]; flag2 = 1; break; } } } // definition of the flag at the mid position if(flag2 == 0){ flag3 =0; for(j = 0; j < frames_number; ++j){ temp[j] = -1; for(k = i + 1; k < pages_number; ++k){ if(frames[j] == pages[k]){ temp[j] = k; break; } } } for(j = 0; j < frames_number; ++j){ if(temp[j] == -1){ pos = j; flag3 = 1; break; } } //definition of flag at the rear position if(flag3 ==0){ max = temp[0]; pos = 0; for(j = 1; j < frames_number; ++j){ if(temp[j] > max){ max = temp[j]; pos = j; } } } frames[pos] = pages[i]; miss++; } printf("\n"); for(j = 0; j < frames_number; ++j){ printf("%d\t", frames[j]); } } printf("\n\nTotal Page miss = %d", miss); return 0; }
Output
Enter the number of frames: 3 Enter the number of pages: 8 Enter page reference string: 4 5 7 4 3 5 7 5 4 -1 -1 4 5 -1 4 5 7 4 5 7 3 5 7 3 5 7 3 5 7 3 5 7
- Read Also – Optimal page replacement in C++