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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Recursion?

Status
Not open for further replies.

cubsfan334

Programmer
Oct 3, 2009
4
US
Hi, I have one more question: How would I make a recursive function? For example I could have these equations:

a1 = (x1 - x2) * t
a2 = (y1 - y2) * t

x1f = 5 * a1
y1f = 5 * a2

I need a do loop that will calculate x1f and y1f when t=1, then plug in the previously generated xf1 for x1 and yf1 for y1 when t=2, etc, and keep doing that.

How would I program this?

Thanks,
cubsfan
 
Not all versions of Fortran will do recursion but you don't need recursion to do what you require
Code:
! Reverse what will happen
x1f = x1
y1f = y1
do t = 1, n, 1
   ! Take the old values
   x1 = x1f
   y1 = y1f
   a1 = (x1 - x2) * t
   a2 = (y1 - y2) * t

   x1f = 5 * a1
   y1f = 5 * a2
end do
You can optimize this a bit by reusing x1, y1 and not bothering with x1f,y1f
Code:
do t = 1, n, 1
   a1 = (x1 - x2) * t
   a2 = (y1 - y2) * t

   x1 = 5 * a1
   y1 = 5 * a2
end do
You could even dispense with a1 and a2
Code:
do t = 1, n, 1
   x1 = 5 * (x1 - x2) * t
   y1 = 5 * (y1 - y2) * t
end do
 
I'm not sure about the first code you posted, but I don't think the 2nd and 3rd will work. I think those simply plug n in for t and solve. What I need is the result for t=2 is dependent on the result of t=1, and the result of t=3 depends on the result of t=2, etc

If that makes sense.
 
Try a dry run with figures - you'll find that all 3 give the same result according to your spec. Alternatively, just print x1, y1, t.

Do x2, y2 always remain the same?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top