fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <mpi.h>
  5.  
  6. #define ARRAY_SIZE 12 // Size of the array
  7.  
  8. int main(int argc, char *argv[]) {
  9. int rank, size, i;
  10. int array[ARRAY_SIZE];
  11. int local_max, global_max = -1;
  12.  
  13. MPI_Init(&argc, &argv);
  14. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  15. MPI_Comm_size(MPI_COMM_WORLD, &size);
  16.  
  17. // Initialize random seed based on current time and rank
  18. srand(time(NULL) + rank * 100); // Add rank to ensure different seeds for different processes
  19.  
  20. // Generate random numbers for the array on process 0
  21. if (rank == 0) {
  22. printf("Array:\n");
  23. for (i = 0; i < ARRAY_SIZE; i++) {
  24. array[i] = rand() % 100;
  25. printf("%d ", array[i]);
  26. }
  27. printf("\n");
  28. }
  29.  
  30. // Broadcast the array from process 0 to all other processes
  31. MPI_Bcast(array, ARRAY_SIZE, MPI_INT, 0, MPI_COMM_WORLD);
  32.  
  33. // Calculate local maximum
  34. int start_index = (ARRAY_SIZE / size) * rank;
  35. int end_index = start_index + (ARRAY_SIZE / size);
  36. local_max = array[start_index];
  37. for (i = start_index + 1; i < end_index; i++) {
  38. if (array[i] > local_max) {
  39. local_max = array[i];
  40. }
  41. }
  42.  
  43. if (rank != 0) {
  44. // Send local maximum to process 0
  45. MPI_Send(&local_max, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
  46. } else {
  47. // Process 0 receives local maxima from all other processes
  48. for (i = 1; i < size; i++) {
  49. int received_max;
  50. MPI_Recv(&received_max, 1, MPI_INT, i, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
  51. if (received_max > global_max) {
  52. global_max = received_max;
  53. }
  54. }
  55.  
  56. // Compare the local maximum of process 0 with the global maximum
  57. if (local_max > global_max) {
  58. global_max = local_max;
  59. }
  60.  
  61. // Print the global maximum on process 0
  62. printf("Global Maximum: %d\n", global_max);
  63. }
  64.  
  65. MPI_Finalize();
  66.  
  67. return 0;
  68. }
  69.  
Success #stdin #stdout #stderr 0.33s 40696KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "int main"
Execution halted