JustPaste
HomeCategoriesAboutDonateContactTerms of UsePrivacy Policy
JustPaste

Free online notepad — write and share instantly

Navigate

  • Home
  • Timeline
  • Categories

Info

  • About
  • Donate
  • Contact

Legal

  • Terms of Use
  • Privacy Policy

© 2026 JustPaste.app. All rights reserved.

Made with ♥ by JustPaste

paging | JustPaste.app
about 5 hours ago2 views
👨‍💻Programming

paging

#include <stdio.h>

int main() {
    int p[] = {1, 2, 3, 1, 4, 5};
    int n = 6, f = 3, frame[10], last[10];
    int choice, faults = 0, ptr = 0;

    printf("1. FIFO\n2. Optimal\n3. LRU\n");
    printf("Enter choice: ");
    scanf("%d", &choice);

    for (int i = 0; i < f; i++) {
        frame[i] = -1;
        last[i] = -1;
    }

    for (int i = 0; i < n; i++) {
        int hit = 0, pos = -1;

        for (int j = 0; j < f; j++) {
            if (frame[j] == p[i]) {
                hit = 1;
                last[j] = i;
                break;
            }
        }

        if (hit) continue;

        if (choice == 1) {  // FIFO
            pos = ptr;
            ptr = (ptr + 1) % f;
        }
        else if (choice == 2) {  // Optimal
            int farthest = -1;

            for (int j = 0; j < f; j++) {
                int k;
                for (k = i + 1; k < n; k++)
                    if (frame[j] == p[k]) break;

                if (k == n) {
                    pos = j;
                    break;
                }

                if (k > farthest) {
                    farthest = k;
                    pos = j;
                }
            }
        }
        else if (choice == 3) {  // LRU
            int least = n + 1;

            for (int j = 0; j < f; j++) {
                if (frame[j] == -1) {
                    pos = j;
                    break;
                }

                if (last[j] < least) {
                    least = last[j];
                    pos = j;
                }
            }
        }
        else {
            printf("Invalid choice!\n");
            return 1;
        }

        frame[pos] = p[i];
        last[pos] = i;
        faults++;
    }

    printf("Page faults: %d\n", faults);
    return 0;
}

⚠️Content was pasted as plain text and auto-formatted as a code block. Use the Code Block button in the editor for proper formatting.

← Back to timeline