Thread: euclids algorithm to find GCD with counter not getting right output

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    25

    euclids algorithm to find GCD with counter not getting right output

    Code:
    #include <stdio.h>
    
    int euclid(int a,int b, int c)
    {
    	if(b==0){
    		c++;
            return a;
    		
    	}
    	else {
    		c++;
            return euclid(b,a%b, c);
    	}
    }
    
    int main()
    {
    	int n1,n2;
    	int counter;
    	printf("Enter two numbers to find its GCD:");
    	scanf("%d %d",&n1,&n2);
    	printf("The GCD of %d and %d is %d - counter = %d",n1,n2,euclid(n1,n2, counter),counter);
    	return 0;
    }
    Here is my code, when I run it I get this


    Enter two numbers to find its GCD:20
    5
    The GCD of 20 and 5 is 5 - counter = 0

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Well, for starts the greatest common denominator of 20 and 5 is 5... so that answer is correct.

    Your counter is 0 because you are not incrementing it. Passing it into a function sends in a *copy* of counter. When you increment c inside the function it has no effect on anything outside the function. If you want to increment a variable in main, from within a function, you need to pass in a pointer...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Trying to make this counter output something different
    By NinjaFish in forum C Programming
    Replies: 14
    Last Post: 02-16-2011, 05:13 AM
  2. euclids algorithm
    By johngav in forum C Programming
    Replies: 13
    Last Post: 03-15-2010, 12:33 PM
  3. how to find string length without using counter
    By nitinmhetre in forum C Programming
    Replies: 4
    Last Post: 09-03-2007, 06:42 AM
  4. please help me understand the euclids algorithm
    By xerxes1986 in forum C++ Programming
    Replies: 15
    Last Post: 03-02-2005, 08:58 PM
  5. cant find where my error is in the line counter
    By Led Zeppelin in forum C Programming
    Replies: 5
    Last Post: 03-23-2002, 04:06 PM