You are on page 1of 6

Parallel and distributed computing

CODE 1: Vector Addition

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

int main()
{
int a[10],b[10],c[10],n,i,j;
printf("Enter the size of the vectors \n");
scanf("%d",&n);

printf("Enter the elements of first vector\n");


for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

printf("Enter the elements of second vector\n");


for(i=0;i<n;i++)
{
scanf("%d",&b[i]);
}

#pragma omp parallel private(c)


{
printf("\nThe result of vector addition is \n");
for(i=0;i<n;i++)
{
c[i]=a[i]+b[i];
printf("%d ",c[i]);
}
printf("\n");
}
}

OUTPUT:
IMPORTANT POINTS:

There are four variables i,j, n , a and b,c . The data-sharing attribute of
variables, which are declared outside the parallel region, is usually shared.
Therefore, n and a,b are shared variables. The loop iteration variables, however,
are private by default. Therefore, i is private. The variables which are declared
locally within the parallel region are private. Thus c is private.

CODE 2: Vector dot product


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

int main()
{
int a[10],b[10],c[10],n,i,j;
printf("Enter the number of dimentions \n");
scanf("%d",&n);

printf("Enter the elements of first vector\n");


for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

printf("Enter the elements of second vector\n");


for(i=0;i<n;i++)
{
scanf("%d",&b[i]);
}

#pragma omp parallel private(c)


{
printf("\nThe result of dot product of vectors is \n");
for(i=0;i<n;i++)
{
c[i]=a[i]*b[i];
printf("%d ",c[i]);
}
printf("\n");
}
}

OUTPUT:
IMPORTANT POINTS

There are four variables i,j, n , a and b,c . The data-sharing attribute of
variables, which are declared outside the parallel region, is usually shared.
Therefore, n and a,b are shared variables. The loop iteration variables, however,
are private by default. Therefore, i is private. The variables which are declared
locally within the parallel region are private. Thus c is private.

CODE 3: Addition of vectors


#include<iostream>
#include<omp.h>
#include<vector>

using namespace std;


int main()
{
int i,n,f, S[10];
vector<int> a;
vector<int> b;
cout<<"Enter dimensions of vectors \n";
cin>>n;
cout<<"Enter first vector values \n";
for( i=0;i<n;i++)
{
cin>>f;
a.push_back(f);
}
cout<<"Enter second vector values \n";
for(i=0;i<n;i++)
{
cin>>f;
b.push_back(f);
}
cout<<"Vectar addition is performed below \n";
#pragma omp parallel shared(a,b,S)
{

for(i=0;i<n;i++)
S[i]=a[i]+b[i];
}
for(i=0;i<n;i++)
cout<<S[i]<<" ";
cout<<"/n";
return 0;
}
OUTPUT

IMPORTANT POINTS:

The shared(list) clause declares that all the variables in list are shared.
b,S and a are shared variables.

You might also like