Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Sunday, 28 April 2019

IOPP Program No.6. A

Program No.6. A

 Write an OpenMP program (for shared memory multiprocessor architecture) to multiply the two matrices using the brute force approach. Display the appropriate environment variables to demonstrate parallel programming.

Solution:

#include <stdio.h>
#include<omp.h>
int main()
{
  int r1, r2, c1, c2, i, j, k,tid,nthreads,chunk=10;
  int A[10][10],B[10][10],C[10][10];


  printf("Enter number of rows and columns of first matrix : \n");
  scanf("%d%d", &r1, &c1);
  printf("Enter elements of first matrix : \n");

  for (i = 0; i < r1; i++)
    for (j = 0; j < c1; j++)
      scanf("%d", &A[i][j]);

  printf("Enter number of rows and coluimns of second matrix : \n");
  scanf("%d%d", &r2, &c2);

  if (r2 != c1){
   printf("The matrices can't be multiplied with each other.\n");
   exit(0);
  }

  printf("Enter elements of second matrix : \n");

  for (i = 0; i < r2; i++)
    for (j = 0; j < c2; j++)
      scanf("%d", &B[i][j]);

#pragma omp parallel shared(A,B,C,nthreads,chunk) private(tid,i,j,k)
{
tid = omp_get_thread_num();
if(tid==0)
{
nthreads=omp_get_num_threads();
printf("Starting matrix multiple example with %d threads.\n",nthreads);
}
printf("Thread %d starting matrix multiply...\n", tid);
  #pragma omp for schedule (static,chunk)
    for (i = 0; i < r1; i++) {
      printf("Thread %d did row %d\n",tid,i);
      for (j = 0; j < c2; j++) {
        C[i][j]=0;
        for (k = 0; k < c1; k++) {
          C[i][j] += A[i][k]*B[k][j];
        }
      }
    }
}
    printf("Product of the matrices : \n");

for(i = 0; i < r1; i++)
{
for (j = 0; j < c2; j++)
{
      printf("%d\t", C[i][j]);
}
      printf("\n");

}
  return 0;

}

0 comments:

Post a Comment