fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <omp.h>
  4.  
  5. void prefix_sum(int* input, int* output, int n) {
  6. output[0] = input[0]; // Initialize the first element
  7.  
  8. #pragma omp parallel
  9. {
  10. // Each thread works in parallel on different sections
  11. #pragma omp for
  12. for (int i = 1; i < n; i++) {
  13. output[i] = output[i - 1] + input[i];
  14. }
  15. }
  16. }
  17.  
  18. int main() {
  19. int n;
  20.  
  21. // Get the size of the array from the user
  22. printf("Enter the size of the array: ");
  23. scanf("%d", &n);
  24.  
  25. int* input = (int*)malloc(n * sizeof(int));
  26. int* output = (int*)malloc(n * sizeof(int));
  27.  
  28. // Initialize the input array with values from 1 to n
  29. for (int i = 0; i < n; i++) {
  30. input[i] = i + 1;
  31. }
  32.  
  33. // Calculate prefix sums
  34. prefix_sum(input, output, n);
  35.  
  36. // Output the result
  37. printf("Prefix sums:\n");
  38. for (int i = 0; i < 10 && i < n; i++) {
  39. printf("%d ", output[i]);
  40. }
  41. printf("\n");
  42.  
  43. // Free dynamically allocated memory
  44. free(input);
  45. free(output);
  46.  
  47. return 0;
  48. }
  49.  
Success #stdin #stdout 0s 5296KB
stdin
Standard input is empty
stdout
Enter the size of the array: Prefix sums:
1 3 6 10 15 21 28 36 45 55