/* MCS 572 Wednesday 18 January 2006: broadcast of array of doubles
 * to compile, type: "mpicc broadcast_doubles.c -o broadcast_doubles";
 * to run on 4 processors, type: "mpirun -np 4 broadcast_doubles". */

#include <stdio.h>
#include "mpi.h"

void read_doubles ( int n, double *d );
void write_doubles ( int myid, int n, double *d );

int main ( int argc, char *argv[] )
{
   int myid,numbprocs,n;
   double *data;

   MPI_Init(&argc,&argv);

   MPI_Comm_size(MPI_COMM_WORLD,&numbprocs);

   MPI_Comm_rank(MPI_COMM_WORLD,&myid);

   if (myid == 0) { printf("Give the dimension : "); scanf("%d",&n); }
      
   MPI_Bcast(&n,1,MPI_INT,0,MPI_COMM_WORLD);

   data = (double*)calloc(n,sizeof(double));

   if (myid == 0) read_doubles(n,data);

   MPI_Bcast(data,n,MPI_DOUBLE,0,MPI_COMM_WORLD);

   if (myid != 0) write_doubles(myid,n,data);

   MPI_Finalize();

   return 0;
}

void read_doubles ( int n, double *d )
{
   int i;

   printf("Give %d doubles : \n", n);
   for(i=0; i < n; i++) scanf("%lf",&d[i]);
}

void write_doubles ( int myid, int n, double *d )
{
   int i;

   printf("Node %d writes %d doubles : \n", myid,n);
   for(i=0; i < n; i++) printf("%lf\n",d[i]);
}
