Untitled

q2
 avatar
unknown
plain_text
19 days ago
2.1 kB
4
Indexable
#include <iostream>
using namespace std;

// Constants
const int NUM_FRAMES = 4;  // Number of frames
const int NUM_PAGES = 10;   // Total number of pages (just for simulation)

// Array to simulate memory frames
int memory[NUM_FRAMES];

// Function to initialize memory (empty)
void initMemory() {
    for (int i = 0; i < NUM_FRAMES; i++) {
        memory[i] = -1;  // -1 means empty frame
    }
}

// Function to print current state of memory
void printMemory() {
    cout << "Memory: ";
    for (int i = 0; i < NUM_FRAMES; i++) {
        if (memory[i] != -1)
            cout << memory[i] << " ";
        else
            cout << "X ";  // X means empty frame
    }
    cout << endl;
}

// Function to simulate page request
void requestPage(int pageNum) {
    bool pageFound = false;

    // Check if the page is already in memory
    for (int i = 0; i < NUM_FRAMES; i++) {
        if (memory[i] == pageNum) {
            pageFound = true;
            cout << "Page " << pageNum << " is already in memory at frame " << i << endl;
            printMemory();
            return;
        }
    }

    // If page not found, replace the first empty frame or replace frame 0 (FIFO)
    for (int i = 0; i < NUM_FRAMES; i++) {
        if (memory[i] == -1) {
            memory[i] = pageNum;
            cout << "Page " << pageNum << " loaded into frame " << i << endl;
            printMemory();
            return;
        }
    }

    // All frames are full, replace page in frame 0 (FIFO replacement)
    memory[0] = pageNum;
    cout << "Page " << pageNum << " loaded into frame 0, replacing old page." << endl;
    printMemory();
}

int main() {
    int pageNum;

    // Initialize memory
    initMemory();

    // Main simulation loop
    while (true) {
        // Get user input for page number
        cout << "Enter page number to request (-1 to exit): ";
        cin >> pageNum;

        // Exit condition
        if (pageNum == -1) {
            break;
        }

        // Handle page request
        requestPage(pageNum);
    }

    return 0;
}
Leave a Comment