os12
Q1)
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#define ARRAY_SIZE 1000
int main(int argc, char *argv[]) {
int rank, size;
int i;
int array[ARRAY_SIZE];
int local_sum = 0;
double local_avg;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Seed random number generator based on rank
srand(rank);
// Generate random numbers
for (i = 0; i < ARRAY_SIZE; i++) {
array[i] = rand() % 1000; // Generate numbers between 0 and 999
}
// Calculate local sum
for (i = 0; i < ARRAY_SIZE; i++) {
local_sum += array[i];
}
// Calculate local average
local_avg = (double)local_sum / ARRAY_SIZE;
// Reduce sum across all processes
int global_sum;
MPI_Reduce(&local_sum, &global_sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
// Reduce average across all processes
double global_avg;
MPI_Reduce(&local_avg, &global_avg, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if (rank == 0) {
printf("Total sum: %d\n", global_sum);
printf("Average: %.2f\n", global_avg / size);
}
MPI_Finalize();
return 0;
}
Q2)
#include <stdio.h>
#include <stdlib.h>
#define MAX_REQUESTS 100
#define MAX_BLOCKS 200
void clook(int *requests, int n_requests, int start_position, int direction) {
int head_movement = 0;
int current_position = start_position;
int i;
printf("Order of request servicing:\n");
if (direction == 0) { // Right direction
for (i = start_position; i <= MAX_BLOCKS; i++) {
for (int j = 0; j < n_requests; j++) {
if (requests[j] == i) {
printf("%d ", i);
head_movement += abs(i - current_position);
current_position = i;
break;
}
}
}
for (i = 0; i < start_position; i++) {
for (int j = 0; j < n_requests; j++) {
if (requests[j] == i) {
printf("%d ", i);
head_movement += abs(i - current_position);
current_position = i;
break;
}
}
}
} else { // Left direction
for (i = start_position; i >= 0; i--) {
for (int j = 0; j < n_requests; j++) {
if (requests[j] == i) {
printf("%d ", i);
head_movement += abs(i - current_position);
current_position = i;
break;
}
}
}
for (i = MAX_BLOCKS; i >= start_position; i--) {
for (int j = 0; j < n_requests; j++) {
if (requests[j] == i) {
printf("%d ", i);
head_movement += abs(i - current_position);
current_position = i;
break;
}
}
}
}
printf("\nTotal head movement: %d\n", head_movement);
}
int main() {
int requests[MAX_REQUESTS];
int n_requests, start_position, direction;
printf("Enter the number of disk requests: ");
scanf("%d", &n_requests);
printf("Enter the disk requests:\n");
for (int i = 0; i < n_requests; i++) {
scanf("%d", &requests[i]);
}
printf("Enter the starting head position: ");
scanf("%d", &start_position);
printf("Enter the direction (0 for right, 1 for left): ");
scanf("%d", &direction);
clook(requests, n_requests, start_position, direction);
return 0;
}