#include <stdio.h>
#include <mpi.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int my_rank, size, num_elements;
int *X;
int *subX;
int *avg;
int *low;
int *high;
num_elements=5;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
if (my_rank == 0) {
printf("Please provide the length of the array:\n"); scanf("%d", &num_elements
); if (num_elements % size != 0) {
printf("Error: The number of elements must be divisible by the number of processes.\n"); MPI_Abort(MPI_COMM_WORLD, 1);
}
X
= malloc(num_elements
* sizeof(int)); for (int i = 0; i < num_elements; i++) {
printf("Please provide number for the location X[%d]: ", i
); }
}
// Allocate memory for all processes
subX
= malloc((num_elements
/ size
) * sizeof(int)); avg
= malloc(size
* sizeof(int)); low
= malloc(size
* sizeof(int)); high
= malloc(size
* sizeof(int)); MPI_Scatter(X, num_elements / size, MPI_INT, subX, num_elements / size, MPI_INT, 0, MPI_COMM_WORLD);
// Calculate average
int subXavgN = 0;
for (int l = 0; l < num_elements / size; l++) {
subXavgN += subX[l];
}
int subXavg = subXavgN / (num_elements / size);
// Find minimum and maximum
int temps = subX[0];
int tempb = subX[0];
for (int l = 0; l < num_elements / size; l++) {
if (temps > subX[l]) {
temps = subX[l];
}
if (tempb < subX[l]) {
tempb = subX[l];
}
}
// Gather results at process 0
MPI_Gather(&subXavg, 1, MPI_INT, avg, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Gather(&temps, 1, MPI_INT, low, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Gather(&tempb, 1, MPI_INT, high, 1, MPI_INT, 0, MPI_COMM_WORLD);
if (my_rank == 0) {
for (int i = 0; i < size; i++) {
}
for (int i = 0; i < size; i++) {
}
for (int i = 0; i < size; i++) {
}
free(X
); // Free the memory allocated for X }
MPI_Finalize();
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxtcGkuaD4KI2luY2x1ZGUgPHN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