Riley Muscha
Riley Muscha

Reputation: 3

Variable for While loop not being recognized as initialized

I am trying to use a variable as the parameter for my while loop, like shown below.

int compChoice;
while (compChoice < 8){

        compChoice = rand() % 8 + 0;
        cout << compChoice;
    }

My goal is to have a random number generated until an 8 is the output. The issue is that my compiler (visual studio pro 2013) is telling me the variable is not initialized. I removed the while loop and left the variable there and retried, and the compiler then told me the variable compChoice is unreferenced. I also tried just using the last two lines and it worked perfectly. I think I'm doing something wrong with the argument, but I can't figure out what. Any help would be greatly appreciated.

Upvotes: 0

Views: 2046

Answers (3)

Theo.Fanis
Theo.Fanis

Reputation: 454

In your example, your program will never end.

 rand() % 8;

generates numbers between 0 and 7. So you need:

rand() % 8 + 1;

to generate numbers between 1 and 8.

Also, you will need to initialize rand with:

#include <ctime>

and:

srand(time(NULL));

before the random generation, and

int compChoice=0;

before the loop

Upvotes: 2

cdhowie
cdhowie

Reputation: 168998

Your while condition is reading the contents of compChoice before you have assigned compChoice a value. Consider using a do-while loop instead, which will execute the loop body once before checking the condition:

int compChoice;
do {
    compChoice = rand() % 8;
    cout << compChoice;
} while (compChoice < 8);

However, this won't even work as you desire it to because rand() % 8 is guaranteed to be less than 8 by the definition of the modulus operation. As you have written your code, the loop will never terminate (unless the uninitialized value in compChoice is already less than 8 when it is first read).

Perhaps you meant rand() % 9 or rand() % 8 + 1? But this doesn't even make sense, as it's just an expensive way to assign 8 to compChoice. It seems like you need to take a step back and figure out what you are even trying to do here.

Upvotes: 2

Jesper Juhl
Jesper Juhl

Reputation: 31467

You are not initializing compChoice before you use it in the loop. So, it has an undefined value.

Upvotes: 0

Related Questions