os10
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;
double sum = 0;
double average;
int array[ARRAY_SIZE];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
if (rank == 0) {
// Generate random numbers
for (i = 0; i < ARRAY_SIZE; i++) {
array[i] = rand() % 1000; // Generate numbers between 0 and 999
}
}
// Broadcast the array to all processes
MPI_Bcast(array, ARRAY_SIZE, MPI_INT, 0, MPI_COMM_WORLD);
// Calculate local sum
double local_sum = 0;
for (i = 0; i < ARRAY_SIZE; i++) {
local_sum += array[i];
}
// Reduce the sum across all processes
MPI_Reduce(&local_sum, &sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if (rank == 0) {
// Calculate the average
average = sum / ARRAY_SIZE;
printf("Sum of the array: %.2f\n", sum);
printf("Average of the array: %.2f\n", average);
}
MPI_Finalize();
return 0;
}
Q2)
#include <stdio.h>
#include <stdlib.h>
void cscan(int requests[], int n, int start, int direction, int total_blocks) {
int total_head_movements = 0;
int current_head = start;
int i, j;
printf("Head Movement Sequence: %d", current_head);
if (direction == -1) {
// Move left
for (i = current_head; i >= 0; i--) {
for (j = 0; j < n; j++) {
if (requests[j] == i) {
total_head_movements += abs(current_head - i);
printf(" -> %d", i);
current_head = i;
break;
}
}
}
// Move to the end
for (i = total_blocks - 1; i >= current_head; i--) {
for (j = 0; j < n; j++) {
if (requests[j] == i) {
total_head_movements += abs(current_head - i);
printf(" -> %d", i);
current_head = i;
break;
}
}
}
} else {
// Move right
for (i = current_head; i < total_blocks; i++) {
for (j = 0; j < n; j++) {
if (requests[j] == i) {
total_head_movements += abs(current_head - i);
printf(" -> %d", i);
current_head = i;
break;
}
}
}
// Move to the beginning
for (i = 0; i < current_head; i++) {
for (j = 0; j < n; j++) {
if (requests[j] == i) {
total_head_movements += abs(current_head - i);
printf(" -> %d", i);
current_head = i;
break;
}
}
}
}
printf("\nTotal Head Movements: %d\n", total_head_movements);
}
int main() {
int n;
printf("Enter the number of disk requests: ");
scanf("%d", &n);
int requests[n];
printf("Enter the disk request string: ");
for (int i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}
int start;
printf("Enter the starting head position: ");
scanf("%d", &start);
int direction;
printf("Enter the direction (1 for right, -1 for left): ");
scanf("%d", &direction);
int total_blocks;
printf("Enter the total number of disk blocks: ");
scanf("%d", &total_blocks);
cscan(requests, n, start, direction, total_blocks);
return 0;
}