r/programminghelp • u/gestapolio • Dec 19 '20
C++ My while loop won't end (C++)
Hey guys, I don't understand why my while loop doesn't end in the code below. It is supposed to stop when n<=2 but when it's value is 1 it keeps going infinitely. If someone knows what I'm doing wrong I'd love the help!
Here's the code:
#include <iostream>
using namespace std;
int main()
{
int l=1;
int lmax=0;
int nmax=0;
int ni;
for (int n=456;n<1110;n++){
ni=n;
while(n>=2){
if (n%2==0){
n=n/2;
cout <<n<< " pair"<<endl;
}else{
n=3*n+1;
cout <<n<<" impair"<< endl;
}
l=l+1;
cout<<l<<" iterations"<<endl;
if (n==1){
break;
}
}
if (l>lmax){
lmax=l;
nmax=ni;
}
}
cout <<"La sequence maximale dure " <<lmax<<" itterations et a un nombre initial de "<<nmax<<endl;
return 0;
}
4
Upvotes
4
u/marko312 Dec 19 '20
Since you modify
nuntil it reaches1,nis1when the loop step and condition run -nis incremented to2every time.