Q. Addition of array elements using two processors?
In this example we have to find sum of all elements of an array A of size n. We will divide n elements in 2 groups of roughly equivalent size. The first [n/2] elements are added by first processor P0 and last [n/2] elements by 2nd processor P1. The two sums then are added to obtain the final result. The program is given below:
Program for P0
#include
#define n 100
int main(int argc, char **argv) {
int A[n];
int sum0 =0, sum1=0,sum;
MPI_Init(&argc, &argv);
for( int i=0;i
scanf("%d", &A[i]);
MPI_Send( &n/2, n/2, MPI_INT,1, 0, MPI_COMM_WORLD);
for(i=1; i
sum0+=A[i];
sum1=MPI_Recv(&n/2, n/2, MPI_INT,1, 0, MPI_COMM_WORLD);
sum=sum0+sum1;
printf("%d",sum);
MPI_Finalize();
}
Program for P1,
int func( int B[int n])
{
MPI_Recv(&n/2, n/2, MPI_INT,0, 0, MPI_COMM_WORLD);
int sum1=0 ;
for (i=0; i2; i++)
sum1+=B[i];
MPI_Send( 0, n/2, MPI_INT,0, 0, MPI_COMM_WORLD);
}