-1

I am fairly new to PHP and I am trying to solve this problem where I need to make a for loop to generate 10 random numbers from the range (1,20) and then output whether they are odd or even.

I am so stuck on this though. So far I have this below, but I know its wrong somewhere. Any help or guidance would be much appreciated.

$rand120 = rand(1, 20); 

for($rand120 = 10; $rand120 <= 20; $rand120++); 
{ 
    echo "$rand120"."<br/>"; 
} 

if ($rand120 % 2 === 0) { 
    echo "$rand120 is even </br>"; 
} else { 
    echo "$rand120 is odd </br>"; 
}
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
madoreo
  • 33
  • 2
  • 9
  • 1
    Side note: Please don't use ticks to highlight every single line of code. You can highlight your code, then hit CTRL-K. It will indent it properly. – Funk Forty Niner Aug 11 '17 at 13:34
  • 1
    Why is there a semicolon `;` after the for-loop? – Qirel Aug 11 '17 at 13:34
  • @Qirel they just stealth edited https://stackoverflow.com/revisions/45636524/4 Edit: and I rolled it back to a previous revision. – Funk Forty Niner Aug 11 '17 at 13:39
  • Please [don't overwrite](https://stackoverflow.com/revisions/45636524/4) your original post https://stackoverflow.com/revisions/45636524/1 (and fixed indentation revisions) after being commented on. People have posted answers. I have rolled the question back to a previous revision. – Funk Forty Niner Aug 11 '17 at 13:39
  • Okay bro jees. I was just making it easier for new post readers. No stealth business going on here. – madoreo Aug 11 '17 at 13:45
  • @madoreo *"No stealth business going on here."* - Well, by "stealth", this means that there were no comments included in the area that you can write that you made a mistake, and/or added an explanation "in" the answer and underneath your original post stating that that was what you tried and did not work. I'm just trying to help you "learn the ropes" on Stack ;-) *Welcome to Stack Overflow*. – Funk Forty Niner Aug 11 '17 at 13:48
  • @madoreo did you need unique random numbers, or might there be duplicates? I just want to clarify your question. – mickmackusa Aug 12 '17 at 10:31
  • @mickmackusa no there can be duplicates on the output – madoreo Aug 13 '17 at 00:05

4 Answers4

5

rand() will only return one random number, not a range of numbers. The two parameters is for minimum and maximum value. If you want 20 random values, you need to use that in a loop.

for ($i = 0; $i < 10; $i++) {
    $value = rand(1, 20);
    if ($value % 2 === 0) { 
        echo "$value is even </br>"; 
    } else { 
        echo "$value is odd </br>"; 
    }
}

This, however, will not ensure they are unique. If you want that, you need to add it to an array, and check it each time you generate a new number, like shown below. This will loop the while until there are 10 elements in the array, and only add a new element when it doesn't exist in the array already.

$array = array();
while (count($array) < 10)) {
    $value = rand(1, 20);
    if (!in_array($value, $array) {
        $array[] = $value;
        if ($value % 2 === 0) { 
            echo "$value is even </br>"; 
        } else { 
            echo "$value is odd </br>"; 
        }
    }
}
Qirel
  • 25,449
  • 7
  • 45
  • 62
2

Hey you are on the right track!

Where I think you got a little off base is that you need to create a random number ten times. Whereas you created only one random number.

See my example below with explanations.

<?php

//create a for loop that will do something 10 times in row
for ($i=0;$i<10;$i++) {

    //every time the loop runs, lets create a random number
    //between 1 and 20 using the rand() function
    $currentRandomNumber = rand(1,20);

    //now, if the random number we made on this loop iteration
    //leaves no remainder when divided by two, it must be even,
    //otherwise it must be odd
    if ($currentRandomNumber % 2 === 0) {
        echo $currentRandomNumber . ' is even.';
    } else {
        echo $currentRandomNumber . ' is odd.';
    }
}

?>

Happy learning!

scramlo
  • 105
  • 6
1
for($i = 0; $i < 10; $i++)
{ 
    $rand120 = rand(1, 20);
    echo "$rand120"."<br/>"; 

    if ($rand120 % 2 === 0) { 
        echo "$rand120 is even </br>"; 
    } else { 
        echo "$rand120 is odd </br>"; 
    }

} 

Explanation

If you want to generate 10 random numbers you should start by looping 10 times. Also rand() returns a single number within the range you give to the function. Therefore, you must call rand every interaction in loop for getting a new random number between 1 and 20.

As you want to tell whether the number is odd or even for every number the if statement ought to go inside the for loop as well.

Carlos Afonso
  • 1,927
  • 1
  • 12
  • 22
0

There is nothing wrong with the other answers on this page. I would like to show you some alternative practices.

Consider this code: (Demo)

for($i=0; $i<10; ++$i){
    echo $rand=rand(1,20),' is ',($rand&1?'odd':'even'),'<br>';
}

Output:

17 is odd
16 is even
17 is odd
4 is even
3 is odd
7 is odd
13 is odd
6 is even
4 is even
18 is even
  • The for loop doesn't change much compared to the other answer. Only the position of the ++ incrementation. I always position my ++ before the variable (when it doen't affect the value differently to do so) as standard practice because it has been proven to be faster than "post-incrementing" ($i++) in benchmarks that I have read. This improvement is a micro-optimization that will go unnoticed by your users virtually every time, but I still do it.
  • PHP allows you to declare a variable while echoing it. This makes the code more condensed, but also makes it a little uglier (IMO). Just something to show you.
  • When concatenating strings in an echo, I always use commas instead of dots. Like my statement about pre-incrementing with ++, using commas is a micro-optimization that performs the same function with a tiny improvement in terms of speed.
  • I have written an inline-conditional to determine odd or even. This is used to reduce the total lines necessary to achieve the desired result. Some people do not like inline-conditionals, but they do not bother me as long as they are not too convoluted (e.g. do not contain more nested inline conditionals).
  • It is good practice to write DRY code. This means instead of writing everything twice like this:

    if($rand&1){
        echo "$rand is odd<br>";
    }else{
        echo "$rand is even<br>";
    }
    

    You should only write the static components once. My original snippet obeys this technique. The following is another way (but it actually uses more lines of code and more echos):

    echo "$rand is ";
    if($rand&1){
        echo 'odd';
    }else{
        echo 'even';
    }
    echo '<br>';
    
  • Lastly, I have implemented the less intuitive bitwise method of determining odd numbers (&1). Demo The advantage here is speed of execution (but again on the scale of your project, it is likely to go unnoticed). I just use this as standard practice.

Opinions on which of these techniques should be used in this case will vary from programmer to programmer, I just wanted to take the opportunity to explain what can be done differently.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136