Comp Sci C++ Why the loop going in infinite loop?

  • Thread starter Thread starter Raghav Gupta
  • Start date Start date
  • Tags Tags
    C++ Infinite Loop
AI Thread Summary
The discussion focuses on resolving an infinite loop issue in a C++ program designed to calculate the GCD (HCF) of two numbers. The original code incorrectly placed the initialization of the variable 'i' within the loop, causing it to reset on each iteration. Suggestions included using debugging statements to track variable values and ensuring the initialization occurs outside the loop. After adjustments, the corrected code successfully computes the HCF without entering an infinite loop. The final solution effectively demonstrates proper loop control and variable management in C++.
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;
    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();
}
 
Physics news on Phys.org
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
 
  • Like
Likes 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;
    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();
}
 
  • Like
Likes NascentOxygen

Similar threads

Replies
2
Views
3K
Replies
14
Views
4K
Replies
8
Views
1K
Replies
3
Views
1K
Replies
3
Views
2K
Replies
7
Views
2K
Replies
10
Views
2K
Back
Top