fork download
  1. #include <mpi.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. int main(int argc, char** argv) {
  6. int rank, size;
  7. int local_max, global_max;
  8. int array[] = {5, 12, 7, 21, 9, 19, 3, 8}; // Example array
  9. int n = sizeof(array) / sizeof(array[0]); // Size of the array
  10. int local_size;
  11.  
  12. // Initialize MPI environment
  13. MPI_Init(&argc, &argv);
  14. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  15. MPI_Comm_size(MPI_COMM_WORLD, &size);
  16.  
  17. // Divide the array among processes
  18. local_size = n / size; // Assumes the array size is divisible by number of processes
  19. int local_array[local_size];
  20.  
  21. MPI_Scatter(array, local_size, MPI_INT, local_array, local_size, MPI_INT, 0, MPI_COMM_WORLD);
  22.  
  23. // Find the local maximum
  24. local_max = local_array[0];
  25. for (int i = 1; i < local_size; i++) {
  26. if (local_array[i] > local_max) {
  27. local_max = local_array[i];
  28. }
  29. }
  30.  
  31. // Use MPI_Reduce to find the global maximum
  32. MPI_Reduce(&local_max, &global_max, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD);
  33.  
  34. // The root process (rank 0) prints the global maximum
  35. if (rank == 0) {
  36. printf("The largest element in the array is: %d\n", global_max);
  37. }
  38.  
  39. // Finalize MPI environment
  40. MPI_Finalize();
  41.  
  42. return 0;
  43. }
Success #stdin #stdout #stderr 0.33s 40316KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "int main"
Execution halted