fork download
  1. #include <stdio.h>
  2. #include <omp.h>
  3.  
  4. int main() {
  5. int n = 10;
  6. int a[n], b[n], c[n];
  7.  
  8. // Initialize arrays
  9. for (int i = 0; i < n; ++i) {
  10. a[i] = i;
  11. b[i] = i * 2;
  12. }
  13.  
  14. // Work sharing with parallel for
  15. #pragma omp parallel for
  16. for (int i = 0; i < n; ++i) {
  17. c[i] = a[i] + b[i];
  18. }
  19.  
  20. printf("Vector Addition using parallel for:\n");
  21. for (int i = 0; i < n; ++i) {
  22. printf("c[%d] = %d\n", i, c[i]);
  23. }
  24.  
  25. // Work sharing with sections
  26. #pragma omp parallel sections
  27. {
  28. #pragma omp section
  29. {
  30. for (int i = 0; i < n/2; ++i) {
  31. c[i] *= 2;
  32. }
  33. }
  34. #pragma omp section
  35. {
  36. for (int i = n/2; i < n; ++i) {
  37. c[i] *= 3;
  38. }
  39. }
  40. }
  41.  
  42. printf("\nVector Modification using sections:\n");
  43. for (int i = 0; i < n; ++i) {
  44. printf("c[%d] = %d\n", i, c[i]);
  45. }
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
Vector Addition using parallel for:
c[0] = 0
c[1] = 3
c[2] = 6
c[3] = 9
c[4] = 12
c[5] = 15
c[6] = 18
c[7] = 21
c[8] = 24
c[9] = 27

Vector Modification using sections:
c[0] = 0
c[1] = 6
c[2] = 12
c[3] = 18
c[4] = 24
c[5] = 45
c[6] = 54
c[7] = 63
c[8] = 72
c[9] = 81