1. ## iterative equation function

hi, im trying to write a program to solve the equation
A(n) = 2A(n-1)-3A(n-2) for n>1.
A(0) = 1 and A(1) = 2.

I've already wrote a recursive program to solve it but am trying to get an iterative version to work. The code I am using for the iterative version is below:
Code:
```int A(int n)
{
int a, b;

a = n-1;
b = n-2;

if(a==0||b==0)
a=1;
if(a==1||b==1)
a=2;
while(a>0&&b>1)
{
n = 2*a-3*b;
}

return n;
}```
I am not entirely sure where I am going wrong, but this code leads to an infinite loop of nothing, and I cannot come up with a way of iterating a and b to get the desired result. I have also tried while loops and nested for loops without much luck. If anyone can point me in the right direction, I'd be grateful.

2. the infinite loop arises because you never decrement the value of a or b in the while loop. Therefore, once you get in the loop the value of a and b never change and therefore the loop will never end, once it starts that is. NO comment whether the iterative solution is the same as the recursive, only why you get the infinite loop.

3. Here's what i would have done:
Code:
```int A( int n )
{
int i, x, y = 2, z = 1;

if( n <= 1 )
x = n+1;
else
for( i=2; i<=n; i++ ) {
x = 2*y - 3*z;
z = y;
y = x;
}

return x;
}```
Hope that helps you.

4. Thanks for the help guys. Money, you're function does the trick. I wouldn't have got that one. Seems obvious now. Nice one.

5. it would interest me to see this as a macro, I can't do it, but it probably can be done.

6. it would interest me to see this as a macro, I can't do it, but it probably can be done.
Why?

This is not what the preprocessor is for! Just 'cos it can be done doesn't mean that it should be done...

7. >it would interest me to see this as a macro
This isn't what I would call macro material, but yes, it can be done:
Code:
```#define A(n,r) \
do { \
int i, y = 2, z = 1; \
if( n <= 1 ) \
r = n+1; \
else { \
for( i=2; i<=n; i++ ) { \
r = 2*y - 3*z; \
z = y; \
y = r; \
} \
} \
} while ( 0 )```