c-----------------------------------------------------------
c Chapter 5: Next composition of n into k parts(p50)
c-----------------------------------------------------------
c   Name of subroutine: NEXCOM
c
c   Algorithm:Generating next composition of n into k parts
c
c   input:    n=6, k=3
c   complier: f77 nexcom_2.f
c-----------------------------------------------------------

      parameter(n=6,k=3)
      logical mtc
      dimension r(k)
      mtc=.false.
    4 call nexcom(n,k,r,mtc)
      write (*,8), (r(i),i=1,k)
    8 format (1x,3(i2,1x))
      if(mtc) goto 4
      stop
      end 

c-----Subroutine begins here   -----------------------------
      subroutine nexcom(n,k,r,mtc)
      integer r(k),t,h
      logical mtc
   10 if(mtc)goto 20
      r(1)=n
      t=n
      h=0
      if(k.eq.1)goto 15
      do 11 i=2,k
   11 r(i)=0
   15 mtc=r(k).ne.n
      return
   20 if(t.gt.1) h=0
   30 h=h+1
      t=r(h)
      r(h)=0
      r(1)=t-1
      r(h+1)=r(h+1)+1
      goto 15
      end

