Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Do loop in ascending and descending order

Status
Not open for further replies.

Vahid9

Technical User
Jul 28, 2016
23
CA
Hello,

I have the following code which generates a 3-d grid between 0 and nmax (usually the three nmax's are around 100):

program Mesh
implicit none
integer, parameter :: npts=64
integer::ntot,n,n1,n2,n3,nmax(3), nstart(3),tmp(3),k(3,npts)

nmax(1)=4; nmax(2)=4; nmax(3)=4
nstart(1)=1; nstart(2)=1; nstart(3)=1
ntot=nmax(1)*nmax(2)*nmax(3)

do n1=nstart(1),nmax(1)
do n2=nstart(2),nmax(2)
do n3=nstart(3),nmax(3)
n=(n1-1)*nmax(2)*nmax(3)+(n2-1)*nmax(3)+n3
k(1,n)=n1-1
k(2,n)=n2-1
k(3,n)=n3-1
enddo
enddo
enddo

do n=1,ntot
print*, n, k(1,n), k(2,n), k(3,n)
enddo
END

The printout for the first 10 lines is:

1 0 0 0
2 0 0 1
3 0 0 2
4 0 0 3
5 0 1 0
6 0 1 1
7 0 1 2
8 0 1 3
9 0 2 0
10 0 2 1

What I need to print out is:

1 0 0 0
2 0 0 1
3 0 0 2
4 0 0 3
5 0 1 3
6 0 1 2
7 0 1 1
8 0 1 0
9 0 2 0
10 0 2 1

Here, the last column shows a continuous increase and then decrease so the numbers change smoothly. I would need to apply this change for columns 2 to 4.

I would appreciate any hints as to how to make this change.

Thank you,

Vahid


 
Hello,

I found a not-so-elegant way to do this:

For a 2-d grid, I use the following:
n=0
do n2=nstart(2),nmax(2)
if (MOD(n2,2)==0) then
do n3=nstart(3),nmax(3)
n=n+1
k(2,n)=n2-1
k(3,n)=n3-1
enddo
else
do n3=nmax(3),nstart(3),-1
n=n+1
k(2,n)=n2-1
k(3,n)=n3-1
enddo
endif
enddo

There might be better ways to do this but the above works.

Thanks,
Vahid
 
Maybe something like this?

Code:
program updown
    integer i, iv, iinc
    integer j, jv, jinc
    integer k, kv, kinc
    integer nmax

    write(*,'("Nmax ?:",$)')
    read(*,*) nmax

    iv = 0 ; iinc = -1
    jv = 0 ; jinc = -1
    kv = 0 ; kinc = -1

    do i = 1, 2*nmax
        call step ( iv, iinc )
        do j = 1, 2*nmax
            call step ( jv, jinc )
            do k = 1, 2*nmax
                call step ( kv, kinc )
                write(*,'(i4,i4,i4)') iv, jv, kv
            end do
        end do
    end do

contains

    subroutine step(val, inc)
        integer val, inc
        val = val + inc
        if ( val > nmax-1  .or.  val < 0) then
            inc = -inc
            val = val + inc
        end if
    end subroutine step

end program updown
 
Thank you Salgerman. Your solution is far more elegant than mine. I need to remove the duplicate lines but that is easy.

Best wishes,
Vahid
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top