hamburger
hamburger

Reputation: 1435

Assignment in do-while/while doesn't work as expected

I want to assign a random value between 48 and 122 to $num except for the value 79.

So to slove this I tried a do-while and a while loop to solve the problem. I tested it, but it doesn't work as expected and it ends in an endless loop.

while($num != 79){
    $num =  rand(48, 122);
};

or:

do {
    $num = rand(48, 122);
} while ($num != 79);

So why doesn't this work as I want it to? Can anyone tell me where my mistake is?

$num shout be a number between 48 and 122 but NOT 79.

Upvotes: 3

Views: 126

Answers (3)

Yazan
Yazan

Reputation: 6082

declare $num with value 79 to make sure loop starts and the loop will quit when $num!=79

$num = 79; // to make sure the loop will iterate at least once
while( $num==79 ){ 
    $num =  rand(48, 122);
}

as per your request, excluding 111 too, modify the condition as below:

while( $num==79 || $num==111)

do-while will use the same condition, and no need to assign 79 as initial value, as the do-while will run at least once.

$num = 0; //just to declare the variable
do {
    $num = rand(48, 122);
} while ($num == 79); // you can use || here too: while ($num == 79 || $num == 111)

Upvotes: 4

Abderrahman Msd
Abderrahman Msd

Reputation: 109

try this code

$num = 0;
while(true){
   $num = rand(48,122);
   if( $num != 79){
      break;
   }
}

Upvotes: -2

the-noob
the-noob

Reputation: 1342

In both cases the logic is wrong, you're repeating the loop while your number is not 79

You should repeat the loop if the number is 79:

$num = 79;// assign value to avoid Notice error 
while($num == 79){ 
    $num =  rand(48, 122);
};

or:

do {
    $num = rand(48, 122);
} while ($num == 79);

Upvotes: 6

Related Questions