Search⌘ K

Solution Review: Even or Odd

Explore how to use Perl's conditional statements by learning to check if a number is even or odd. Understand the modulus operator and if statement to control program flow based on number properties.

We'll cover the following...

Let’s look at the solution of the last lesson before getting into the explanation:

Perl
$number = 5; # change value to run for your desired case
$temp = -1;
if($number % 2 == 0){
$temp = 0;
}
else{
$temp = 1;
}

Explanation

For a given $number, we used the if statement to check its modulus with 2. If it is 0 then the $temp will be set to 0, otherwise $temp will be set to 1.

The % operator returns the remainder of two numbers. For instance, 5 % 2 is 1 because 5 divided by 2 leaves a remainder of 1.