/* -----------------------------------------------------!
! The current code has a purpose:                       !
! (1) demonstrate firstprivate variables.               !
! (2) reduction variables.                              !
!-------------------------------------------------------!
! Xiaoxu Guan at LSU HPC.                               !
! March 07, 2016                                        !
!----------------------------------------------------- */

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

int main () 
{
    int i,id,nosize,noprocs;
    const int  nsize = 50;
    double temp,tsum,totsum,answer;
    double array_a[nsize-1];


    noprocs = omp_get_num_procs();

    nosize = nsize;
    for( i = 0; i < nosize; i++ ) { array_a[i] = (double) i; }
    
    tsum = 0.0;
    totsum = 0.0;


#pragma omp parallel default(none) private(id,i) shared(nosize,noprocs,array_a) \
        firstprivate(tsum) reduction(+: totsum)
   {
      id = omp_get_thread_num();

#pragma omp for 
      for( i = 0; i < nosize; ++i ) { tsum += array_a[i]; }

      printf("%3d  %12.2f\n", id, tsum);


#pragma omp for schedule(static,1)
      for( i = 0; i < noprocs; i++ ) { totsum += tsum; }
   }

    printf("\n");

    answer = (double) 0.5*(nsize-1)*nsize;
    printf("totsum = %12.2f\n", totsum);
    printf("correct answer = %12.2f\n", answer);

}

