Thread: Having some problem with a GCF program

  1. #1
    Registered User
    Join Date
    Aug 2009

    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:

    #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)
            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;
        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.


  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    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.

  3. #3
    Registered User
    Join Date
    Aug 2009
    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, 11:10 AM
  2. Program Termination Problem
    By dacbo in forum C Programming
    Replies: 3
    Last Post: 01-23-2006, 02: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