C*****************************************************************************
C
C               Example 12 : Omp_Maxof_Elements_ReductionOp.f
C
C   Objective : Write an OpenMP program to print Largest element of
C               an array
C               This example demonstrates the use of
C               OMP_PARALLEL DO loop and REDUCTION operation
C
C   Input     : Number of elements of an array
C               User has to set OMP_NUM_THREADS environment variable for
C               n number of threads
C
C   Output    : Each thread checks with its available iterations and 
C               finally master thread prints the maximum value in the array
C
C*****************************************************************************

       program MaxOfElements
       integer SIZE
       parameter (SIZE=100, MAXIMUM=65536)
       real Array(SIZE), LargeNumber

       integer OMP_GET_THREAD_NUM, ThreadID
       integer NoofElements, Seed

       real MaxOfNumber, CheckValue

 	    print*,"Enter the number of elements"
 	    read(*,*) NoofElements

       if((NoofElements .le. 0) .or. (NoofElements .gt. SIZE)) then
          print*,"Input is Wrong."
          print*,"Please try with another number less than",SIZE+1
          print*,"Or greater than 0"
          goto 100
       endif

       Seed = MAXIMUM
       do i = 1, NoofElements
 		    Array(i) = ran(Seed)
          print*,"Array(",i,")=",Array(i)
       enddo

C$OMP PARALLEL DO REDUCTION(MAX:LargeNumber)
       do j = 1, NoofElements
          LargeNumber = MaxOfNumber(Array(j), LargeNumber)
       enddo

 	    CheckValue = Array(1)
 	    do i = 2, Noofelements
 		    if (Array(i) .gt. CheckValue) then
 			    CheckValue = Array(i)
          endif
       enddo

 	    if (CheckValue .eq. LargeNumber) then
 		    print*,"The Maximum value is same using serial computation"
          print*,"and openmp directive"
 	    else 
 		    print*,"The Maximum value is not same using serial computation"
          print*,"and openmp directive"
       endif

 	    print*,"The largest number in the array is", LargeNumber

100    end


C This function returns the maximum of two numbers.

       real function MaxOfNumber(ArrayElement, Number)
       real ArrayElement
       real Number

       if(ArrayElement .gt. Number) then
          Number = ArrayElement
       endif

       MaxOfNumber = Number
       return
       end

        
       
