1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ Why the loop going in infinite loop?

  1. Nov 21, 2015 #1
    1. The problem statement, all variables and given/known data
    I have to find GCD or HCF of two numbers.

    2. Relevant equations


    3. The attempt at a solution
    Code (C):

    #include<iostream.h>
    #include<conio.h>
    void main()
    {
        clrscr();
        int i,m,n,temp;
        cout<<"Enter two numbers\n";
        cin>>m>>n;
        do
        {
        if(n>m)
        {
         temp=n;
         n=m;
         m=temp;   // this loop I think it is correct but still it is going to an infinite loop.
        }
         i=n;
         if(m%i==0&&n%i==0)
         break;
         i--;
        }while(i>=1);
        cout<<"The HCF is\t"<<i;
        getch();
    }
     
     
  2. jcsd
  3. Nov 21, 2015 #2
    Use some printf statements for debugging (or cout)

    See if your code is doing what you think it is doing.

    I usually define a debug flag and have debugging statements such as

    if(debug) printf("%d %d\n", num, num2);

    etc
     
  4. Nov 21, 2015 #3

    NascentOxygen

    User Avatar

    Staff: Mentor

    Where you give i its starting value, you have incorrectly placed the statement so that it is executed during every pass through the loop. You should place it where it gets executed once only.
     
  5. Nov 21, 2015 #4
    Thanks,
    Now I am able to execute and get correct output.
    My code looks like this now,
    Code (C):
    #include<iostream.h>
    #include<conio.h>
    void main()
    {
        clrscr();
        int i,m,n,temp;
        cout<<"Enter two numbers\n";
        cin>>m>>n;
        i=n;

        do
        {

          if(m%i==0&&n%i==0)
          break;
          i--;
        }while(i>=1);
         cout<<"The HCF is\t"<<i;
         getch();
    }
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted