So I made a while loop for finding all divisors for given numbers and it's the following
int a,b;
int temp =0;
cout << "Enter the first number : ";
cin >> a;
cout << "Enter the second number : ";
cin >> b;
int smallestNum = a<b?a:b;
while(true)
{
temp ;
if(a%temp == 0 && b%temp == 0) cout << temp << ", ";
if (temp == smallestNum) break;
}
cout << "are all the divisors for both numbers";
and it worked like expected but when i tried to do the same in a for loop it didn't go as planned
int a,b;
int temp;
cout << "Enter the first number : ";
cin >> a;
cout << "Enter the second number : ";
cin >> b;
temp = a<b?a:b;
for (int i; i == temp; i )
{
if(a%i==0 && b%i==0) cout << i << ", ";
}
cout << "are all the divisors for both numbers";
I can't even find the problem in my code to fix it, how can I fix it????
CodePudding user response:
for
loop will iterate as long as condition is true
, your condition is i == temp
which is (in general) false
, you should change it to i != temp