fork download
  1. #include <stdio.h>
  2. #include <mpi.h>
  3.  
  4. int main(int argc, char *argv[]) {
  5. int pid, nprocs;
  6. int N; // Size of the array
  7. int *tableau = NULL; // Pointer to hold the user-entered array
  8. int taille_par_process, somme_locale = 0, somme_totale = 0;
  9.  
  10. MPI_Init(&argc, &argv);
  11. MPI_Comm_rank(MPI_COMM_WORLD, &pid);
  12. MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
  13.  
  14. if (pid == 0) {
  15. // Process 0 asks the user for the size of the array
  16. printf("Enter the size of the array (divisible by %d): ", nprocs);
  17. scanf("%d", &N);
  18.  
  19. // Allocate memory for the array
  20. tableau = (int *)malloc(N * sizeof(int));
  21.  
  22. // Get the elements from the user
  23. printf("Enter %d integers:\n", N);
  24. for (int i = 0; i < N; i++) {
  25. scanf("%d", &tableau[i]);
  26. }
  27. }
  28.  
  29. // Broadcast the size of the array to all processes
  30. MPI_Bcast(&N, 1, MPI_INT, 0, MPI_COMM_WORLD);
  31.  
  32. // Check if the size is divisible by the number of processes
  33. if (N % nprocs != 0) {
  34. if (pid == 0) {
  35. printf("Error: Array size must be divisible by the number of processes.\n");
  36. }
  37. MPI_Finalize();
  38. return -1;
  39. }
  40.  
  41. // Calculate the size of each process's portion
  42. taille_par_process = N / nprocs;
  43. int sous_tableau[taille_par_process]; // Local array for each process
  44.  
  45. // Scatter the array to all processes
  46. MPI_Scatter(tableau, taille_par_process, MPI_INT,
  47. sous_tableau, taille_par_process, MPI_INT,
  48. 0, MPI_COMM_WORLD);
  49.  
  50. // Each process calculates the sum of its portion
  51. for (int i = 0; i < taille_par_process; i++) {
  52. somme_locale += sous_tableau[i];
  53. }
  54. printf("Process %d: Local sum = %d\n", pid, somme_locale);
  55.  
  56. // Reduce the local sums into the total sum at process 0
  57. MPI_Reduce(&somme_locale, &somme_totale, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
  58.  
  59. // Process 0 prints the total sum
  60. if (pid == 0) {
  61. printf("Total sum of the array elements = %d\n", somme_totale);
  62. free(tableau); // Free the allocated memory
  63. }
  64.  
  65. MPI_Finalize();
  66. return 0;
  67. }
  68.  
Success #stdin #stdout #stderr 0.33s 40548KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "int main"
Execution halted