Having some problem with a GCF program

This is a discussion on Having some problem with a GCF program within the C++ Programming forums, part of the General Programming Boards category; So, I am new to C++ and only just started. I have bought a book called C++ Without Fear by ...

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    2

    Having some problem with a GCF program

    So, I am new to C++ and only just started. I have bought a book called C++ Without Fear by Brian Overland, and I am having a problem with one of the exercises to do with the Greatest Common Factor.

    The source code is:

    Code:
    #include <iostream>
    using namespace std;
    
    int gcf(int a, int b);
    
    int main() {
        int a = 0, b = 0;
        while(1) {
            cout << "Enter a number (0 to quit): ";
            cin >> a;
            if (a==0)
            break;
            cout << "Enter 2nd number: ";
            cin >> b;
            cout << "GCF = " << gcf(a, b) << endl;
        }
        return 0;
    }
    
    int gcf(int a, int b) {
        if (a % b == 0)
        return b;
        else
        return gcf(b, a % b);
        cout << gcf(b, a % b);
    }
    That much I have managed to understand, but now after he explains it, he says to do an exercise where I revise the program so it shows all the steps involved in the algorithm.

    For example-
    GCF(300, 500) =>
    GCF(500, 300) =>
    GCF(300, 200) =>
    GCF(200, 100) =>
    GCF = 100

    Right now, all that the code does is immediately give the answer.
    Please help me out.

    Thanks!

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,434
    The cout in your gcf() function is unreachable.
    One way or another, it hits a return before then.

    Put it at the start, and just print a,b
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Aug 2009
    Posts
    2
    Thanks, working fine now

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Multi Thread Program Problem
    By ZNez in forum C Programming
    Replies: 1
    Last Post: 01-03-2009, 10:10 AM
  2. Program Termination Problem
    By dacbo in forum C Programming
    Replies: 3
    Last Post: 01-23-2006, 01:34 AM
  3. Replies: 20
    Last Post: 06-12-2005, 11:53 PM
  4. Console Program Problem
    By Breach23 in forum C++ Programming
    Replies: 3
    Last Post: 10-19-2001, 12:35 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21