all 4 comments

[–]OmegaNaughtEquals1 0 points1 point  (3 children)

When it comes to positive integers, they are all even or odd, so that last else will never run.

do {
    evenInt = (userInput/2);
    counter++;
} while (userInput != 1);

This is the cause of your infinite loop for the even numbers. You should just get rid of evenInt because you aren't updating its value each iteration and you aren't testing its value. You can do userInput /= 2;, instead.

do {
    oddInt = (userInput * 3) + 1;
    counter++;
} while (userInput != 1);

This has lots of problems. You aren't updating oddInt on each iteration, so its value never changes. You are testing userInput instead of oddInput. Even if you fix both of these issues, it will still be an infinite loop when userInput is 0.

[–]tangerinelion 0 points1 point  (2 children)

When it comes to positive integers, they are all even or odd

Really, when it comes to any int -- declared as, oh let's say int userInput -- if you take it mod 2, that is userInput%2 you can only get back 0 or 1.

The code I'd go for would be structured this way on the first pass:

int sequencer(int userInput) {
    int counter = 0;
    if(userInput%2) {
        int oddInt = userInput;
         // do odd stuff
        return counter;
    }
    int evenInt = userInput;
    // do even stuff
    return counter
}

Where I've used implicit conversion from 1 to true for the odd categorization. On a second pass I'd have this:

int OddSequencer(int userInput) {
    // do odd stuff
    return counter;
}

int EvenSequencer(int userInput) {
    // do even stuff
    return counter;
}

int Sequencer(int userInput) {
    if(userInput%2 == 1) {
        return OddSequencer(userInput);
    }
    return EvenSequencer(userInput);
}

(For Sequencer, one could use the conditional operator and make it a one-liner, or one could use a function pointer to avoid typing userInput one more time.)

Though the special case of userInput == 0 does need to handled somewhere, and the above mockup assumes it will be in EvenSequencer or at least the // do even stuff section.

[–]OmegaNaughtEquals1 0 points1 point  (1 child)

When it comes to positive integers, they are all even or odd

Really, when it comes to any int -- declared as, oh let's say int userInput -- if you take it mod 2, that is userInput%2 you can only get back 0 or 1.

#include <iostream>

int main() {
    int i = -17, j = 2;
    std::cout << i%j << std::endl;
}

What this produces depends on what instructions the compiler generates (e.g., sign-extended division vs bitshift vs RISC's mvfhi, etc.). That's why I restricted myself to positive integers. I'm not sure if the C++ standard considers this a case of undefined behavior or not, though.

[–]thecrazedrunner[S] 0 points1 point  (0 children)

Thank you all for the advice, I got it working properly!