Why does the below code not produce any output ?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • radha gogia
    New Member
    • Feb 2015
    • 56

    Why does the below code not produce any output ?

    Code:
    #include<stdio.h>
    int gcd(int m ,int n)
    {
    if(m%n==0)
    return n;
    else return(n,m%n);
    }
    
    int main()
    {
    int x,y;
    printf("enter two numbers");
    scanf("%d",&x);
    scanf("%d",&y);
    int a=gcd(x,y);
    if(a==1)
    {
    printf("the numbers are co-prime");
    }
    return 0;
    }

    Here when I run the code just after taking input there is no output so what is the reason for it , I gave input as 7 and 9 and I didn't get any output ,plz clarify this .
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    What is gcd returning? If m is 7 and n is 9 then m%n is 7%9 which is 7. So then m%n ==0 is false. Therefore you return (n,m%n). This looks odd but it is a valid a valid expression using the comma operator. SO first there's n and then there's m%n and that's what is returned.

    Two things, first write your code such that you can see the return value from your functions. Second, I have the feeling this gcd function is recursive but you have omitted the gcd in that return statement.

    Post again and let me know what happened.

    Comment

    • radha gogia
      New Member
      • Feb 2015
      • 56

      #3
      First it would be
      gcd(7,9) --> gcd(9,7)--> gcd(7,2) -->gcd(2,1) now since m%n==0 hence it should return n which is equal to 1 , where's the problem then ?why is the code not producing the output ?

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        If you look inside the gcd function you see:

        Code:
        int gcd(int m ,int n)
         {
         if(m%n==0)
         return n;
         else return(n,m%n);   <----------------
         }
        So it's not doing this: gcd(7,9) --> gcd(9,7)--> gcd(7,2) -->gcd(2,1)

        I think the code should be:

        Code:
        int gcd(int m ,int n)
         {
         if(m%n==0)
         return n;
         else return gcd(n,m%n);   <----------------revised
         }
        This is a case where stepping though the code with a debugger can save a lot of time.

        Comment

        Working...