OneCompiler

os2

192

Q1)
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>

#define MAX_BLOCKS 100

bool allocated[MAX_BLOCKS] = {false};

void showBitVector(int n) {
printf("Bit Vector:\n");
for (int i = 0; i < n; i++) {
if (allocated[i]) {
printf("1 ");
} else {
printf("0 ");
}
}
printf("\n");
}

void createNewFile(int n) {
int block;
do {
printf("Enter block number to allocate (0 to %d, -1 to exit): ", n - 1);
scanf("%d", &block);
if (block >= 0 && block < n) {
if (allocated[block]) {
printf("Block %d is already allocated.\n", block);
} else {
allocated[block] = true;
printf("Block %d allocated.\n", block);
}
} else if (block != -1) {
printf("Invalid block number. Please enter a number between 0 and %d.\n", n - 1);
}
} while (block != -1);
}

void showDirectory(int n) {
printf("Directory:\n");
printf("Allocated blocks: ");
for (int i = 0; i < n; i++) {
if (allocated[i]) {
printf("%d ", i);
}
}
printf("\n");
}

int main() {
int n;
printf("Enter the number of blocks on disk: ");
scanf("%d", &n);

srand(time(NULL)); // Initialize random number generator

char choice;
do {
    printf("\nMenu:\n");
    printf("a) Show Bit Vector\n");
    printf("b) Create New File\n");
    printf("c) Show Directory\n");
    printf("d) Exit\n");
    printf("Enter your choice: ");
    scanf(" %c", &choice);

    switch (choice) {
        case 'a':
            showBitVector(n);
            break;
        case 'b':
            createNewFile(n);
            break;
        case 'c':
            showDirectory(n);
            break;
        case 'd':
            printf("Exiting...\n");
            break;
        default:
            printf("Invalid choice!\n");
    }
} while (choice != 'd');

return 0;

}

Q2)
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>

#define ARRAY_SIZE 1000

int main(int argc, char *argv[]) {
int rank, size, i;
int local_sum = 0, global_sum = 0;
int array[ARRAY_SIZE];

MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);

// Initialize random number generator
srand(rank);

// Generate random numbers for each process
for (i = 0; i < ARRAY_SIZE; i++) {
    array[i] = rand() % 100; // Generate random numbers between 0 and 99
}

// Calculate local sum
for (i = 0; i < ARRAY_SIZE; i++) {
    local_sum += array[i];
}

// Reduce the local sum to get the global sum
MPI_Reduce(&local_sum, &global_sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);

// Process 0 prints the global sum
if (rank == 0) {
    printf("Global sum: %d\n", global_sum);
}

MPI_Finalize();

return 0;

}