Write the simulation program to implement demand paging and show the page scheduling and total number of page faults according to the FIFO page replacement algorithm. Assume the memory of n frames.
Reference String : 8, 5, 7, 8, 5, 7, 2, 3, 7, 3, 5, 9, 4, 6, 2

#include <stdio.h>
#include <stdlib.h>

#define MAX_FRAMES 100

// Function to find the index of the page in the frames array
int find_page(int frames[], int num_frames, int page) {
    for (int i = 0; i < num_frames; i++) {
        if (frames[i] == page) {
            return i;
        }
    }
    return -1;
}

// Function to simulate FIFO page replacement algorithm
void fifo_page_replacement(int reference_string[], int num_references, int num_frames) {
    int frames[MAX_FRAMES];
    int page_faults = 0;
    int front = 0; // Pointer to the oldest page in FIFO

    // Initialize all frames to -1 (indicating empty)
    for (int i = 0; i < num_frames; i++) {
        frames[i] = -1;
    }

    printf("Reference String: ");
    for (int i = 0; i < num_references; i++) {
        printf("%d ", reference_string[i]);
    }
    printf("\n");

    printf("Page Scheduling:\n");

    for (int i = 0; i < num_references; i++) {
        int page = reference_string[i];
        int page_index = find_page(frames, num_frames, page);

        if (page_index == -1) { // Page fault
            // Replace the oldest page
            frames[front] = page;
            front = (front + 1) % num_frames;
            page_faults++;

            printf("Reference: %d | Frames: ", page);
            for (int j = 0; j < num_frames; j++) {
                printf("%d ", frames[j]);
            }
            printf("(Page fault)\n");
        } else {
            printf("Reference: %d | Frames: ", page);
            for (int j = 0; j < num_frames; j++) {
                printf("%d ", frames[j]);
            }
            printf("(No page fault)\n");
        }
    }

    printf("Total Page Faults: %d\n", page_faults);
}

int main() {
    // Define the reference string and the number of frames
    int reference_string[] = {8, 5, 7, 8, 5, 7, 2, 3, 7, 3, 5, 9, 4, 6, 2};
    int num_references = sizeof(reference_string) / sizeof(reference_string[0]);
    int num_frames = 3; // Number of memory frames

    // Simulate FIFO page replacement
    fifo_page_replacement(reference_string, num_references, num_frames);

    return 0;
}