LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Help in C with the collatz problem. (https://www.linuxquestions.org/questions/programming-9/help-in-c-with-the-collatz-problem-901061/)

smag 09-04-2011 12:24 PM

Help in C with the collatz problem.
 
I have wrote the code in Python and it works, but in C I have some problems.
Can someone help me, please?
This is my code:
Quote:

#include <stdio.h>

int main(void){
int N=0;
for(N=3;N<5;N++){
printf("N: %d",N);
int End=0;
while (End==0){

if(N%2==0){
N=N/2;
}
else if(N==1){
End=1;
}
else{
N=(N*3)+1;
}
}
}
printf("End\n");
return 0;
}

dwhitney67 09-04-2011 12:36 PM

N will never be 1; thus the app will never exit the while-loop.

Nylex 09-04-2011 01:06 PM

Also, you should be using [code] tags, rather than [quote], to preserve indentation.

ta0kira 09-04-2011 01:44 PM

Quote:

Originally Posted by dwhitney67 (Post 4461283)
N will never be 1; thus the app will never exit the while-loop.

Actually, if you run it you'll see that it does exit the while loop (3-->10-->5-->16-->8-->4-->2-->1) but since the condition that makes it exit from the while loop is N==1, N is never >=5. So the program certainly "works"; however, it's up to interpretation whether or not "do what I meant, not what I wrote" has been fulfilled.
Kevin Barry

PS It could be that N needs to be copied when used in the loop.

dwhitney67 09-04-2011 02:23 PM

Quote:

Originally Posted by ta0kira (Post 4461341)
Actually, if you run it ...

Something for me to consider in the future before I submit a post. :D

smag 09-04-2011 04:12 PM

Quote:

Originally Posted by ta0kira (Post 4461341)
PS It could be that N needs to be copied when used in the loop.

Thanks I found the problem.

Quote:

Originally Posted by Nylex (Post 4461307)
Also, you should be using code tags, rather than quote, to preserve indentation.

Ok, I will do it.


All times are GMT -5. The time now is 04:53 AM.