title: Looping through an MPI ring in C
body: <p>I'm having trouble figuring out how to do multiple iterations in my MPI code. Just from testing multiple for loops in different spots tells me I am doing something wrong. Part of our instructions are to pass the token around the ring multiple times specified in the command line arguments, but i cant seem to get it to work correctly by even hard coding the iterations. I left the top for loop in(Which doesn't work) but commented out the others.  </p>
  
  <p>This is probably a more complicated task than I am anticipating.
  Any help is appreciated</p>
  
  <pre><code>#include &lt;mpi.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(int argc, char* argv[])
  {
      double starttime, endtime;
      MPI_Init(&amp;argc, &amp;argv);
      starttime = MPI_Wtime();
      int world_rank;
      int world_size;
  
      for (int i = 0; i &lt; 3; i++)
  
          MPI_Comm_rank(MPI_COMM_WORLD, &amp;world_rank);
          MPI_Comm_size(MPI_COMM_WORLD, &amp;world_size);
  
  //pass the token
  
          int token =1000;
  
  //for (int i = 0; i &lt; 3; i++)
  //{
      if (world_rank == 0)
      {
          token = 0;
          MPI_Send(&amp;token, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);
  
          MPI_Recv(&amp;token, 1, MPI_INT, world_size - 1, 0, MPI_COMM_WORLD, 
          MPI_STATUS_IGNORE);
  
          printf("FINAL TOKEN %d\n", token);
      }
      else if(world_rank &lt; world_size - 1 )
      {
          MPI_Recv(&amp;token, 1, MPI_INT, world_rank-1, 0, MPI_COMM_WORLD, 
          MPI_STATUS_IGNORE);
  
          printf("%d has token %d sending to %d\n", world_rank, token, 
          world_rank+1);
          token = token + 2;
  
          MPI_Send(&amp;token, 1, MPI_INT, world_rank+1, 0, MPI_COMM_WORLD);
          }
      else
          {
          MPI_Recv(&amp;token, 1, MPI_INT, world_rank-1, 0, MPI_COMM_WORLD, 
          MPI_STATUS_IGNORE);
          printf("%d has token %d sending to %d\n", world_rank, token, 
          world_rank+1);
          token = token + 2;
          MPI_Send(&amp;token, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
          }
      endtime = MPI_Wtime();
      printf("That took %f seconds\n",endtime-starttime);
      }
      MPI_Finalize();
  
      return 0;
  }
  </code></pre>
  
  <p>Here's the compile and run output:</p>
  
  <pre><code>$ mpicc -std=c99 test.c
  $ mpirun -np 3 ./a.out
  1 has token 0 sending to 2
  That took 0.000187 seconds
  2 has token 2 sending to 3
  That took 0.000145 seconds
  FINAL TOKEN 4
  That took 0.000180 seconds
  FINAL TOKEN 4
  That took 0.000212 seconds
  2 has token 2 sending to 3
  That took 0.000202 seconds
  2 has token 2 sending to 3
  That took 0.000233 seconds
  1 has token 0 sending to 2
  That took 0.000291 seconds
  1 has token 0 sending to 2
  That took 0.000322 seconds
  FINAL TOKEN 4
  That took 0.000244 seconds
  </code></pre>