You are on page 1of 1

#include <stdio.

h>
#include <stdlib.h>
#include <mpi.h>

#define ARRAY_SIZE 100

int main(int argc, char** argv) {


int rank, size;
int i, 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 the array with values 1 to ARRAY_SIZE


for (i = 0; i < ARRAY_SIZE; i++) {

array[i] = rand() % 100;


printf("%d\t",array[i]);
}

// Divide the work among the processes


int chunk_size = ARRAY_SIZE / size;
int* chunk = (int*) malloc(chunk_size * sizeof(int));

// Scatter the chunks to each process


MPI_Scatter(array, chunk_size, MPI_INT, chunk, chunk_size, MPI_INT, 0,
MPI_COMM_WORLD);

// Calculate the sum of the chunk assigned to this process


int local_sum = 0;
for (i = 0; i < chunk_size; i++) {
local_sum += chunk[i];
}

// Reduce the local sums to a global sum


MPI_Reduce(&local_sum, &sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);

if (rank == 0) {
printf("The sum is %d\n", sum);
}

free(chunk);
MPI_Finalize();
return 0;
}

You might also like