Hi, so I wrote this program to find the GCD of two numbers, the program runs just fine its that I also need it to display how many times it loops, I cant get it to do that. Can some one please tell me what I'm doing wrong, Thanks!

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

int GCD(int a, int b)
{
    while( 1 )
    {
		        a = a % b;
		if( a == 0 )
			return b;
		b = b % a;

        if( b == 0 )
			return a;
    }
}

int main()
{
	loopcounter++=1
	int x, y;
	

	cout << "This program allows calculating the GCD\n";
	cout << "Value 1: ";
	cin >> x;
	cout << "Value 2: ";
	cin >> y;

	cout << "\nThe Greatest Common Divisor of "
	     << x << " and " << y << " is " << GCD(x, y) << endl;  
	cout << "the number of loops=" << loopcounter << endl;

	getch();
}

I also need it to display how many times it loops, I cant get it to do that.

int GCD(int a, int b)
{
    while( 1 )
    {
		        a = a % b;
		if( a == 0 )
			return b;
		b = b % a;

        if( b == 0 )
			return a;
    }
}

The easiest way would be to declare a global integer value and increment it with each loop cycle. Such as..

int loopcounter = 0;

int GCD(int a, int b)
{
    while( 1 )
    {
              loopcounter++:
		        a = a % b;
		if( a == 0 )
			return b;
		b = b % a;

        if( b == 0 )
			return a;
    }
}

Also get rid of..

loopcounter++=1;

This is wrong because you didn't specify a type. Follow my example and it will work out better. The rest of your code should work fine.

This article has been dead for over six months. Start a new discussion instead.