fork download
  1. #include <iostream> // Include the I/O stream library for input and output operations
  2. #include <omp.h> // Include the OpenMP library for parallel programming
  3. #include <climits> // Include the library for limit constants such as INT_MAX and INT_MIN
  4.  
  5. using namespace std; // Use the standard namespace to avoid prefixing std::
  6.  
  7. // Function to find the minimum element in the array using OpenMP for parallel processing
  8. int min_reduction(int arr[], int n) {
  9. int min_value = INT_MAX; // Start with the largest possible int
  10. #pragma omp parallel for reduction(min: min_value)
  11. for (int i = 0; i < n; i++) {
  12. if (arr[i] < min_value) {
  13. min_value = arr[i];
  14. }
  15. }
  16. return min_value; // Return the minimum value found
  17. }
  18.  
  19. // Function to find the maximum element in the array using OpenMP
  20. int max_reduction(int arr[], int n) {
  21. int max_value = INT_MIN; // Start with the smallest possible int
  22. #pragma omp parallel for reduction(max: max_value)
  23. for (int i = 0; i < n; i++) {
  24. if (arr[i] > max_value) {
  25. max_value = arr[i];
  26. }
  27. }
  28. return max_value; // Return the maximum value found
  29. }
  30.  
  31. // Function to compute the sum of all elements in the array using OpenMP
  32. int sum_reduction(int arr[], int n) {
  33. int sum = 0;
  34. #pragma omp parallel for reduction(+: sum)
  35. for (int i = 0; i < n; i++) {
  36. sum += arr[i];
  37. }
  38. return sum; // Return the total sum of elements
  39. }
  40.  
  41. // Function to compute the average of the elements in the array using OpenMP
  42. double average_reduction(int arr[], int n) {
  43. int sum = 0;
  44. #pragma omp parallel for reduction(+: sum)
  45. for (int i = 0; i < n; i++) {
  46. sum += arr[i];
  47. }
  48. return static_cast<double>(sum) / n; // Calculate and return the average
  49. }
  50.  
  51. int main() {
  52. int *arr, n;
  53.  
  54. cout << "\n enter total no of elements=>";
  55. cin >> n;
  56.  
  57. arr = new int[n];
  58. cout << "\n enter elements=>";
  59. for (int i = 0; i < n; i++) {
  60. cin >> arr[i];
  61. }
  62.  
  63. int min_value = min_reduction(arr, n);
  64. int max_value = max_reduction(arr, n);
  65. int total_sum = sum_reduction(arr, n);
  66. double average = average_reduction(arr, n);
  67.  
  68. cout << "Minimum value: " << min_value << endl;
  69. cout << "Maximum value: " << max_value << endl;
  70. cout << "Sum: " << total_sum << endl;
  71. cout << "Average: " << average << endl;
  72.  
  73. delete[] arr; // Free the allocated memory
  74. }
  75.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
 enter total no of elements=>
 enter elements=>Minimum value: 0
Maximum value: 0
Sum: 0
Average: 0