os28
Q1)
#include <stdio.h>
#include <stdlib.h>
// Function to sort the disk request string in ascending order
void sortRequests(int *requests, int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (requests[j] > requests[j + 1]) {
int temp = requests[j];
requests[j] = requests[j + 1];
requests[j + 1] = temp;
}
}
}
}
// Function to simulate C-LOOK algorithm
int cLook(int *requests, int n, int head) {
// Sort the requests
sortRequests(requests, n);
// Initialize total head movements
int totalHeadMovements = 0;
// Find the index of the head position in the sorted request array
int headIndex = 0;
while (headIndex < n && requests[headIndex] < head) {
headIndex++;
}
// Serve requests in the forward direction
for (int i = headIndex; i < n; i++) {
printf("%d ", requests[i]);
totalHeadMovements += abs(requests[i] - head);
head = requests[i];
}
// If there are more requests, wrap around and serve requests from the beginning
if (headIndex > 0) {
for (int i = 0; i < headIndex; i++) {
printf("%d ", requests[i]);
totalHeadMovements += abs(requests[i] - head);
head = requests[i];
}
}
return totalHeadMovements;
}
int main() {
int n;
printf("Enter the total number of disk blocks: ");
scanf("%d", &n);
int *requests = (int *)malloc(n * sizeof(int));
if (requests == NULL) {
printf("Memory allocation failed\n");
return 1;
}
printf("Enter the disk request string:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}
int head;
printf("Enter the current head position: ");
scanf("%d", &head);
printf("The list of requests served in C-LOOK order:\n");
int totalHeadMovements = cLook(requests, n, head);
printf("\nTotal number of head movements: %d\n", totalHeadMovements);
free(requests);
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;
int array[ARRAY_SIZE];
int sum = 0;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Seed random number generator
srand(rank);
// Generate random numbers for each process
for (int i = 0; i < ARRAY_SIZE; i++) {
array[i] = rand();
}
// Calculate local sum
for (int i = 0; i < ARRAY_SIZE; i++) {
sum += array[i];
}
// Reduce local sum values to find the global sum
MPI_Reduce(&sum, &sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
if (rank == 0) {
printf("The sum of randomly generated 1000 numbers is: %d\n", sum);
}
MPI_Finalize();
return 0;
}