### HELP -Gcf NON-RECURSIVE FUNCTION

closed account (ivDwAqkS)
I don't know if its right, but I am getting the answer I wanted but now I don't know if I am doing the problem right, can someone tell me please?

This is the exercise:
 ``1234567`` ``````"For experts: Revise the gcf function so that it uses an iterative (loop- based) approach. Each cycle through the loop should stop if B is zero; otherwise, it should set new values for A and B and then continue. You’ll need a temporary variable—temp— to hold the old value of B for a couple of lines: temp=b, b=a%b, and a=temp."``````

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849`` ``````#include #include using namespace std; int Gcf(int a, int b); void Print_gcf(int a, int b); int main () { int a = 0, b = 0; cout << "Enter a: "; cin >> a; cout << "Enter b: "; cin >> b; Print_gcf(a, b); cout << "GCF is "<< Gcf(a, b) << endl; return 0; } int Gcf(int a, int b) { int temp; temp=b; b=a%b; a=temp; if(temp==0){ return a; } else{ return a%b; } } void Print_gcf(int a, int b) { int temp; cout << "GCF (" << a << ") " << "(" << b << ") => " << b <0){ temp=b; b=a%b; a=temp; if(temp==0){ cout << a; } cout << "GCF (" << a << ") " << "(" << b << ") => " << b <

Last edited on
closed account (ivDwAqkS)
Please I need help D: someone tell me if I am doing it right or not.
The iterative version of Gcf will require a loop (as your instructions indicate.) And presumably, Print_gcf should be calling Gcf.
Last edited on
closed account (ivDwAqkS)
but if Print_gcf calls Gcf fuction isn't it recursive? if not, how would the problem could be wrote?
Last edited on
 but if we call a fuction isn't it recursive?

No. If a function calls itself directly or indirectly, that is recursive. If funcA calls funcB which doesn't, in turn, call funcA either directly or indirectly, then that is not recursive.
closed account (ivDwAqkS)
how would the problem could be wrote then? could you help me out? because when I write Gcf inside it prints until:

GCF(500, 300) => 300
GCF(300, 200) => 200
GCF(200, 100) => 100
GCF(100, 0) => 0

then if says error the program stopped working and it doesn't print the gcf value
I may have mentioned something earlier about avoiding division by zero.
closed account (ivDwAqkS)
yes but that was with recursive function if you notice. if I leave it like this is it correct too?
Last edited on
Recursive or iterative, one must still avoid division by zero.
Topic archived. No new replies allowed.