title: Matrix multiplication MPI
body: <p>At the university, I was asked a laboratory for parallel programming: parallelize the multiplication of matrices. I wrote an algorithm similar to the example, but the implementation provides a breakpoint. Tell me, please, what can I fix?</p>
  
  <pre><code>#define _CRT_SECURE_NO_WARNINGS
  #include &lt;cstdlib&gt;
  #include &lt;iostream&gt; 
  #include &lt;math.h&gt; 
  #include "mpi.h" 
  #include &lt;stdio.h&gt;
  const int N=4; 
  int main(int argc, char *argv[]) {
      int r,q,myid,numprocs;
      int i0;
      int *b,*c,*loc_a,*loc_c;
      MPI_Init(&amp;argc,&amp;argv);
      MPI_Comm_size(MPI_COMM_WORLD,&amp;numprocs);
      MPI_Comm_rank(MPI_COMM_WORLD,&amp;myid);
      MPI_Status status;
      q=N/numprocs;
      b=new int [N*N];
      c=new int [N*N];
      loc_c=new int[N*N];
      loc_a=new int[q];
      for(int i=0;i&lt;N*N;i++)     {
          c[i]=0;      loc_c[i]=0;     
      }     
      if(myid==0)     {
          for (int j = 0; j&lt;numprocs; j++) {
              for (r = 0; r&lt;q*N; r++) {
                  loc_a[r] = 1; 
              }        
              MPI_Send(&amp;loc_a[0], q*N, MPI_INT, j, 0, MPI_COMM_WORLD); 
          }      
          for (int i = 0; i&lt;N*N; i++) { 
              b[i] = 1; 
          }        
      }     
      MPI_Recv(&amp;loc_a[0], q*N, MPI_INT, 0, 0, MPI_COMM_WORLD, &amp;status);
      for (r = 0; r&lt;N; r++) {
          MPI_Bcast(&amp;b[r*N], N, MPI_INT, 0, MPI_COMM_WORLD);
          i0 = myid*q;
          for (int i = 0; i&lt;q; i++) {
              for (int j = 0; j&lt;N; j++) {
                  loc_c[r*N + i0] += loc_a[i*N + j] * b[r*N + j]; 
              }      
              i0++; 
          }     
          MPI_Reduce(loc_c, c, N*N, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); 
      }     
      if (myid == 0) {
          FILE *f = fopen("result.txt", "w");
          for (int i = 0; i&lt;N; i++) {
              for (int j = 0; j&lt;N; j++) {
                  fprintf(f, "%d\t", c[j*N + i]); 
              }       
              fprintf(f, "\n"); 
          }     
          fclose(f); 
      }
  return 0; 
  MPI_Finalize(); 
  }
  </code></pre>