C++ Why the loop going in infinite loop?

3 replies · 2K views · last reply
Raghav Gupta
Messages
1,010
Reaction score
76

Homework Statement


I have to find GCD or HCF of two numbers.

Homework Equations

The Attempt at a Solution


Code:
#include<iostream.h>
#include<conio.h>
void main()
{
    clrscr();
    int i,m,n,temp;
    count<<"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);
    count<<"The HCF is\t"<<i;
    getch();
}
 
Use some printf statements for debugging (or count)

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
 
  • Like
Likes   Reactions: Raghav Gupta
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.
 
NascentOxygen said:
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.
Thanks,
Now I am able to execute and get correct output.
My code looks like this now,
Code:
#include<iostream.h>
#include<conio.h>
void main()
{
    clrscr();
    int i,m,n,temp;
    count<<"Enter two numbers\n";
    cin>>m>>n;
    i=n;

    do
    {

      if(m%i==0&&n%i==0)
      break;
      i--;
    }while(i>=1);
     count<<"The HCF is\t"<<i;
     getch();
}
 
  • Like
Likes   Reactions: NascentOxygen