# Thread: Ileterative & recursive function

1. ## Ileterative & recursive function

this code should calculate the greates common divisor of 2 integers entered by the user.
Both the recursive & ilterative function should have the same result but they don't.
I can't for the life of me figure out what im doing wrong.
Any help would be much appreciated !

Code:
```#include <stdio.h>
int gcd(int a,int b);
int gcdliterative(int a,int b);

void main(){

int a,b,c,d;
printf("Enter two posetive integers,\n");
printf("that you'd like to see the greatest common divisor off\n");
if ((scanf("%d%d",&a,&b)) != 2){
printf("Error!You needed to input 2 posetive integers, exiting...\n");
exit(1);
}
c = gcd(a,b);
printf("The greatest common divisor off:%d and %d is: %d\n",a,b,c);
printf("Calculating again ,useing a literative loop this time\n");
d = gcdliterative(a,b);
printf("The greatest common divisor off:%d and %d is: %d\n",a,b,d);
}

int gcd(int a,int b){
int r;
if ((r = a % b) == 0)
return b;
else
return gcd(b,r);
}

int gcdliterative(int a,int b){
int r;
while((r = a % b) == 1){
a = b;
b = r;
}
return r;
}```

2. Code:
``` int gcdliterative(int a,int b){
int r;
while((r = a % b) == 1){
a = b;
b = r;
}
return r;
}```
k, you've got the right setup, just a few things out of order.

First off, (r = a % b) == 1, notice in your recursive one how you test if the remainder is 0 then you return, but if it's anything OTHER then 0, you continue on again, right?

Well, you need to apply that same logic here, instead of testing if the value is 1, test if it's not 0, in other words, just do:

(r = a % b) != 0

or you could even just do:

(r = a % b)

Both work the same way.

Next problem is your return, you're returning r, but since the loop goes until r equals 0, the only thing r will ever be returned as is....0!
So instead of returning r, you need to return b, just like you did in the recursive version of the problem.

Here's the working version of the code:
Code:
``` int gcdliterative(int a,int b){
int r;
while((r = a % b)){
a = b;
b = r;
}
return b;
}```
-Hope that helps!

3. Oke cool , thanks very much for your help !