// Libraries
#include <iostream> // Library for input and output operations.
#include <omp.h> // Library OpenMP for parallel programming.
#include <cstdlib> // Library for general utilities like rand() and srand().
#include <ctime> // Library for time() to seed the random number generator.
// Constants
#define ARRAY_SIZE 1000 // Size of the arrays.
#define CHUNK_SIZE 100 // Size of chunks for parallel processing.
#define NUM_DISPLAY 10 // Number of elements to display.
// Namespace
using namespace std; // To not specify explicitly the std namespace for every standard library object or function.
// Function to print the specified first elements of an array.
void print_array(float *array)
{
// Loop through the specified first elements.
for(int i=0; i<NUM_DISPLAY; i++)
{
// Print the current element.
cout<<array[i];
// Print the separator if it's not the last element to print.
if(i<NUM_DISPLAY-1)
{
cout<<" , ";
}
}
// Print a newline at the end.
cout<<endl;
}
// Main
int main()
{
// Display message to inform that it is a parallel operation.
cout<<"ADDITION OF ARRAYS IN PARALLEL\n";
// Declare arrays.
float array_A[ARRAY_SIZE], array_B[ARRAY_SIZE], array_R[ARRAY_SIZE];
// Seed the random number generator.
srand(static_cast<unsigned>(time(0)));
// Fill the arrays with random float values between 0 and 100.
for(int i=0; i<ARRAY_SIZE; i++)
{
array_A[i] = static_cast<float>(rand()) / RAND_MAX * 100;
array_B[i] = static_cast<float>(rand()) / RAND_MAX * 100;
}
// Set the chunk size for parallel processing.
int chunk_size = CHUNK_SIZE;
// Parallel region to add the elements of arrays A and B into resultArray
#pragma omp parallel for \
shared(arrayA, arrayB, resultArray, chunkSize) private(index) \
schedule(static, chunkSize)
// Add corresponding elements of array_A and array_B.
for(int i=0; i<ARRAY_SIZE; i++)
{
array_R[i] = array_A[i] + array_B[i];
}
// Print the specified first elements of each array.
cout<<"\nFirst "<<NUM_DISPLAY<<" elements of Array A: "<<endl;
print_array(array_A);
cout<<"\nFirst "<<NUM_DISPLAY<<" elements of Array B: "<<endl;
print_array(array_B);
cout<<"\nFirst "<<NUM_DISPLAY<<" elements of the Resultant Array: "<<endl;
print_array(array_R);
// Exit the program.
return 0;
}