C++ Why the loop going in infinite loop?

  • Context: Comp Sci 
  • Thread starter Thread starter Raghav Gupta
  • Start date Start date
  • Tags Tags
    C++ Infinite Loop
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 1K views
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();
}
 
Physics news on Phys.org
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