r/programminghelp • • 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

2 comments sorted by

4

u/marko312 Dec 19 '20
for (int n=456;n<1110;n++){

Since you modify n until it reaches 1, n is 1 when the loop step and condition run - n is incremented to 2 every time.

3

u/gestapolio Dec 19 '20

Thanks! Replaced n with i in the for loop and now it works!