- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Hi,
How to write a Fortran code with a variable number of nested loops.
Thank you.
Link Copied
- « Previous
- Next »
44 Replies
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
NESTED DO loops
Suppose we have the following simple program:
program test
parameter (m=4)
dimension ib(m),ie(m),is(m),i(m)
data ib/1,1,1,1/
data ie/3,4,-3,2/
data is/1,2,-2,1/
write(*,*) 'Enter a number >=1,and <=',m
read(*,*)n
if (n.gt.m) stop
if (n.lt.1) stop
call donest(ib,ie,is,n,i)
end
We want to construct: subroutine donest(ib,ie,is,n,i) such as to implement a variable number of NESTED DO-loops.
For example for n=2 we should get the output that the following code yields:
EQUIVELANT CODE:
DO 1 I1=IB(1),IE(1),IS(1)
DO 2 I2=IB(2),IE(2),IS(2)
WRITE(*,*)I1,I2
2 CONTINUE
1 CONTINUE
OUTPUT:
1 1
1 3
2 1
2 3
3 1
3 3
Similarly for n=3 we have:
EQUIVELANT CODE:
DO 1 I1=IB(1),IE(1),IS(1)
DO 2 I2=IB(2),IE(2),IS(2)
DO 3 I3=IB(3),IE(3),IS(3)
WRITE(*,*)I1,I2,I3
3 CONTINUE
2 CONTINUE
1 CONTINUE
OUTPUT:
1 1 1
1 1 -1
1 1 -3
1 3 1
1 3 -1
1 3 -3
2 1 1
2 1 -1
2 1 -3
...
3 1 -3
Correspondigly for n=4, etc
Sample Solution
subroutine donest(ib,ie,is,n,i)
dimension ib(n),ie(n),is(n),i(n)
* Determine if the loops are doable and the exact right bounds
do 2 j=1,n
if (is(j).eq.0) return
k = (ie(j)-ib(j))/is(j)
if ( ib(j).le.ie(j) .and. is(j).gt.0 ) then
ie(j)=ib(j)+ k*is(j)
elseif ( ib(j).ge.ie(j) .and. is(j).lt.0 ) then
ie(j)=ib(j)+ k*is(j)
else
return
endif
2 continue
* Set initial values
do 3 j = 1,n
i(j) = ib(j)
3 continue
* Print all values now (running the innermost loop
4 continue
do 1 in = ib(n),ie(n),is(n)
i(n) = in
write(*,*)(i(j),j=1,n)
1 continue
*
do 10 j = n-1,1,-1
if ( i(j).ne.ie(j) ) then
i(j) = i(j)+is(j)
go to 4
else
i(j) = ib(j)
endif
10 continue
end
*
program test
parameter (m=4)
dimension ib(m),ie(m),is(m),i(m)
data ib/1,1,1,1/
data ie/3,4,-3,2/
data is/1,2,-2,1/
write(*,*) 'Enter a number >=1,and <=',m
read(*,*)n
if (n.gt.m) stop
if (n.lt.1) stop
call donest(ib,ie,is,n,i)
end
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Please start a new thread, rather than reopening one more than three years old.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
I agree, start a new thread.
By the way, is this a problem for a computer science course?
If so, I suggest you think about a solution that involves recursion.
Jim Dempsey
Reply
Topic Options
- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page
- « Previous
- Next »