Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.7 kB
0
Indexable
Never
#include <stdio.h>
#include <stdlib.h>

#define MAX 100

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

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;
    }

    printf("\nReference String: ");
    for (int i = 0; i < numReferences; i++) {
        printf("%d ", referenceString[i]);
    }
    printf("\n\n");

    printf("Step\tPage\tFRAMES\t\tStatus\n");
    printf("----\t----\t--------------------\t------\n");

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

        // Check if page is in frames
        if (isPageInFrames(frames, numFrames, page)) {
            sprintf(status, "Hit");
            pageHits++;
        } else {
            // Page fault: Replace the oldest page
            frames[front] = page;
            front = (front + 1) % numFrames;
            sprintf(status, "Fault");
            pageFaults++;
        }

        // Print the step, page, and frame contents
        printf("%d\t%d\t", i+1, page);
        printFrames(frames, numFrames);
        printf("\t%s\n", status); // Print status on the same line
    }

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

int main() {
    int numReferences, numFrames;
    printf("********NIRAJAN UPRETI**********\n ");
    printf("-------FIFO----------\n");

    // 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