1

there. I'm self learning C++ out of "C++ without fear". There is an exercise dealing with the GCD of 2 numbers that asks to print "GCD(a,b) =>" at each step in the proceedure. I was able to get this working:

int gcd (int a, int b);

int main() {
    int i,j;
    cout << "Enter the first integer" << endl;
    cin >> i;
    cout << "Enter the second integer" << endl;
    cin >> j;
    int k = gcd(i,j);
    cout << "The GCD is " << k << endl; 
    system("PAUSE");
    return 0;
}

int gcd (int a, int b){
    if(b==0){
        cout << "GCF(" << a;
        cout << "," << b;
        cout << ") => " <<endl;
        return a;
    }
    else {
        cout << "GCF(" << a;
        cout << "," << b;
        cout << ") => " << endl;
        return gcd(b,a%b);
    }
}

I was just wondering if there is a nicer way to go about printing each step of finding the GCD. That is, is there a "nicer" way to write this part of the code:

     cout << "GCF(" << a;
     cout << "," << b;
     cout << ") => " << endl;

? Thanks in advance.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
mikeysaxton
  • 37
  • 1
  • 1
  • 3
  • I'd use `std::cout << "GCF(" << a << ',' << b << ") => \n";`. You can just do it once before the `if`, and indeed the `if` can be replaced by `return b ? gcd(b, a % b) : a;`, which means if `b` is non-0 return `gcd(...)` otherwise `a`. – Tony Delroy Apr 17 '15 at 02:00
  • It certainly depends on what you mean by "nicer." You can certainly just use a single `cout` and chain the outputs on a single line if you desire. – Steven Hansen Apr 17 '15 at 02:00
  • I was not aware that you could use the nested quotations in that way. Thanks a bunch! – mikeysaxton Apr 18 '15 at 05:06

3 Answers3

1

You can do something like:

     cout << "GCF(" << a << ',' << b << ") =>" << endl;
l-l
  • 3,804
  • 6
  • 36
  • 42
0

It is not C++ but you could use the C way of printing it which in my opinion looks better in this situation because there are far fewer stream operators, << in the way.

#include <cstdio>

printf("GCF(%d, %d) =>\n", a, b);

But this is a C way of doing things... You could use something like boost::format as is mentioned in this SO answer.

Community
  • 1
  • 1
nonsensickle
  • 4,438
  • 2
  • 34
  • 61
0

try this one

#include<iostream>
#include<conio.h>
using namespace std;

int main(){
  cout << 6+2 <<"\n" << 6-2;
}