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

Friday, 3 May 2019

IOPP Program 5 A

Question:

Write an OpenMP program (for shared memory multiprocessor architecture) to add two matrices. Display the appropriate environment variables to demonstrate parallel programming.

Solution:

#include<stdio.h>
#include<stdlib.h>
#include<omp.h>


int main(int argc,char **argv)
{
        int a[10][10],b[10][10],c[10][10],n;
        int i,tid,nthreads,chunk=10,j;
printf("Enter the size of Matrix\n");
scanf("%d",&n);
        printf("Enter elements of 1st array :\n");
        for(i=0;i<n;i++)
for(j=0;j<n;j++){
                scanf("%d",&a[i][j]);
}
        printf("Enter elements of 2nd array :\n");
        for(i=0;i<n;i++)
for(j=0;j<n;j++){
                scanf("%d",&b[i][j]);
}

        #pragma omp parallel shared(a,b,c,nthreads,chunk) private(tid,i)
        {
                tid = omp_get_thread_num();
                if(tid==0)
                {
                        nthreads=omp_get_num_threads();
                        printf("Starting matrix addition example with %d threads.\n",nthreads);
                }
        printf("Thread %d starting matrix addition...\n", tid);
        #pragma omp parallel for schedule(static,chunk)
        for(i=0;i<n;i++) {
for(j=0;j<n;j++){
                c[i][j]=a[i][j]+b[i][j];
        }
}
        printf("Thread %d ending matrix addition...\n", tid);
        }
        printf("Resultant array :\n");
               for(i=0;i<n;i++){
for(j=0;j<n;j++){
                printf("%d ",c[i][j]);
}
printf("\n");
}
}

0 comments:

Post a Comment