Untitled

mail@pastecode.io avatar
unknown
plain_text
5 months ago
2.2 kB
1
Indexable
#include <stdio.h>
#include <stdlib.h>

#define MAX 100

void printFrames(int frames[], int numFrames) {
    printf("Frames: ");
    for (int i = 0; i < numFrames; i++) {
        if (frames[i] == -1)
            printf("_ ");
        else
            printf("%d ", frames[i]);
    }
    printf("\n");
}

int isPageInFrames(int frames[], int numFrames, int page) {
    for (int i = 0; i < numFrames; i++) {
        if (frames[i] == page) {
            return 1; // Page hit
        }
    }
    return 0; // Page fault
}

void fifoPageReplacement(int referenceString[], int numReferences, int numFrames) {
    int frames[MAX];
    int front = 0, rear = 0, pageFaults = 0, pageHits = 0;
    
    // Initialize frames with -1 indicating empty
    for (int i = 0; i < numFrames; i++) {
        frames[i] = -1;
    }

    for (int i = 0; i < numReferences; i++) {
        int page = referenceString[i];

        // Check if page is in frames
        if (isPageInFrames(frames, numFrames, page)) {
            printf("Page %d -> Hit\n", page);
            pageHits++;
        } else {
            // Page fault: Replace the oldest page
            frames[front] = page;
            front = (front + 1) % numFrames;
            pageFaults++;

            printf("Page %d -> Fault\n", page);
        }

        // Print current frames
        printFrames(frames, numFrames);
    }

    printf("\nTotal Page Faults: %d\n", pageFaults);
    printf("Total Page Hits: %d\n", pageHits);
}

int main() {
    int numReferences, numFrames;
    
    // User input for number of frames
    printf("Enter the number of page frames: ");
    scanf("%d", &numFrames);

    // User input for number of reference strings
    printf("Enter the number of reference strings: ");
    scanf("%d", &numReferences);

    int referenceString[numReferences];
    
    // User input for reference strings
    printf("Enter the reference string (space separated): ");
    for (int i = 0; i < numReferences; i++) {
        scanf("%d", &referenceString[i]);
    }

    // Run FIFO page replacement
    fifoPageReplacement(referenceString, numReferences, numFrames);

    return 0;
}
Leave a Comment