fork download
  1. #include <stdio.h>
  2. #include <mpi.h>
  3. #include <stdlib.h>
  4.  
  5. int main(int argc, char **argv) {
  6. int my_rank, size, num_elements;
  7. int *X;
  8. int *subX;
  9. int *avg;
  10. int *low;
  11. int *high;
  12. num_elements=5;
  13. MPI_Status status;
  14.  
  15. MPI_Init(&argc, &argv);
  16. MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
  17. MPI_Comm_size(MPI_COMM_WORLD, &size);
  18.  
  19. if (my_rank == 0) {
  20. printf("Please provide the length of the array:\n");
  21. scanf("%d", &num_elements);
  22. if (num_elements % size != 0) {
  23. printf("Error: The number of elements must be divisible by the number of processes.\n");
  24. MPI_Abort(MPI_COMM_WORLD, 1);
  25. }
  26. X = malloc(num_elements * sizeof(int));
  27. for (int i = 0; i < num_elements; i++) {
  28. printf("Please provide number for the location X[%d]: ", i);
  29. scanf("%d", &X[i]);
  30. }
  31. }
  32.  
  33. // Allocate memory for all processes
  34. subX = malloc((num_elements / size) * sizeof(int));
  35. avg = malloc(size * sizeof(int));
  36. low = malloc(size * sizeof(int));
  37. high = malloc(size * sizeof(int));
  38. printf("attempting scatter");
  39. MPI_Scatter(X, num_elements / size, MPI_INT, subX, num_elements / size, MPI_INT, 0, MPI_COMM_WORLD);
  40.  
  41. // Calculate average
  42. int subXavgN = 0;
  43. for (int l = 0; l < num_elements / size; l++) {
  44. subXavgN += subX[l];
  45. }
  46. int subXavg = subXavgN / (num_elements / size);
  47.  
  48. // Find minimum and maximum
  49. int temps = subX[0];
  50. int tempb = subX[0];
  51. for (int l = 0; l < num_elements / size; l++) {
  52. if (temps > subX[l]) {
  53. temps = subX[l];
  54. }
  55. if (tempb < subX[l]) {
  56. tempb = subX[l];
  57. }
  58. }
  59.  
  60. // Gather results at process 0
  61. MPI_Gather(&subXavg, 1, MPI_INT, avg, 1, MPI_INT, 0, MPI_COMM_WORLD);
  62. MPI_Gather(&temps, 1, MPI_INT, low, 1, MPI_INT, 0, MPI_COMM_WORLD);
  63. MPI_Gather(&tempb, 1, MPI_INT, high, 1, MPI_INT, 0, MPI_COMM_WORLD);
  64.  
  65. if (my_rank == 0) {
  66. printf("Averages: ");
  67. for (int i = 0; i < size; i++) {
  68. printf("%d ", avg[i]);
  69. }
  70. printf("\nMinimums: ");
  71. for (int i = 0; i < size; i++) {
  72. printf("%d ", low[i]);
  73. }
  74. printf("\nMaximums: ");
  75. for (int i = 0; i < size; i++) {
  76. printf("%d ", high[i]);
  77. }
  78. printf("\n");
  79. free(X); // Free the memory allocated for X
  80. }
  81.  
  82. free(subX);
  83. free(avg);
  84. free(low);
  85. free(high);
  86.  
  87. MPI_Finalize();
  88. return 0;
  89. }
Success #stdin #stdout #stderr 0.31s 40780KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "int main"
Execution halted