0

I recently learned about Collatz's conjecture. I found it fun, so I just wanted to find out if I could create a small program in C capable of checking the numbers up to a defined number and turned out I wasn't. Here is my program

#include <stdlib.h>
#include <stdio.h>

int main()
{
    int n = 5;
    int u;

    for (int i = 0; i < 1000; i++) {
        while(n != 4) {
            u = n;

            if (n % 2 == 0) {
                n = n / 2;
            }
            else {
                n = 3 * n + 1;
            }
        }

        n = u + 1;
        printf("%d verifies the conjecture \n", n);
    }
}

Problem: The output only shows 9's, and won't increment further. I've done the logic (following what my program would do) by hand, and it works, so I'm completely stumped. Let it be reminded that I'm not good in C, I'm still learning, so it's normal if I'm ignorant to really basic things, as I'm learning it as I go. Thanks all.

1
  • 2
    "following what my program would do, by hand'. The next step would be to run the program in a debugger. It will allow you to step thru the program line by line and examine the variable values as it runs. So that you can spot where things start to go wrong. Commented Feb 3, 2022 at 20:59

1 Answer 1

1

You're resetting u in the wrong place:

    while(n != 4)
    {
        u = n;

This sets u to the current value of n after every iteration of the inner loop. Move it to the outside.

    u = n;
    while(n != 4)
    {
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.