title: How are MPI_Scatter and MPI_Gather used from C?
body: <p>So far, my application is reading in a txt file with a list of integers. These integers needs to be stored in an array by the master process i.e. processor with rank 0. This is working fine. </p>
  
  <p>Now, when I run the program I have an if statement checking whether it's the master process and if it is, I'm executing the <code>MPI_Scatter</code> command. </p>
  
  <p>From what I understand this will subdivide the array with the numbers and pass it out to the slave processes i.e. all with rank > 0 . However, I'm not sure how to handle the <code>MPI_Scatter</code>. How does the slave process "subscribe" to get the sub-array? How can I tell the non-master processes to do something with the sub-array? </p>
  
  <p>Can someone please provide a simple example to show me how the master process sends out elements from the array and then have the slaves add the sum and return this to the master, which adds all the sums together and prints it out?  </p>
  
  <p>My code so far:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;mpi.h&gt;
  
  //A pointer to the file to read in.
  FILE *fr;
  
  int main(int argc, char *argv[]) {
  
  int rank,size,n,number_read;
  char line[80];
  int numbers[30];
  int buffer[30];
  
  MPI_Init(&amp;argc, &amp;argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &amp;rank);
  MPI_Comm_size(MPI_COMM_WORLD, &amp;size);
  
  fr = fopen ("int_data.txt","rt"); //We open the file to be read.
  
  if(rank ==0){
  printf("my rank = %d\n",rank);
  
  //Reads in the flat file of integers  and stores it in the array 'numbers' of type int.
  n=0;
  while(fgets(line,80,fr) != NULL) {
    sscanf(line, "%d", &amp;number_read);
    numbers[n] = number_read;
    printf("I am processor no. %d --&gt; At element %d we have number: %d\n",rank,n,numbers[n]);
    n++;
  }
  
  fclose(fr);
  
  MPI_Scatter(&amp;numbers,2,MPI_INT,&amp;buffer,2,MPI_INT,rank,MPI_COMM_WORLD);
  
  }
  else {
  MPI_Gather ( &amp;buffer, 2, MPI_INT, &amp;numbers, 2, MPI_INT, 0, MPI_COMM_WORLD); 
  printf("%d",buffer[0]);
  }
  MPI_Finalize();
  return 0;
  }
  </code></pre>