Open In App

Perl Program to Find Out Odd and Even Numbers From a List of Numbers

The article focuses on discussing different ways to find out how to segregate odd and even numbers from a given list of numbers in Perl.

Prerequisite: The user must be familiar with Perl and has an idea about conditional statements and loops.



Problem Statement

Given a list of integers, find out which of them are odd and which of them are even.

Input: arr = (10, 5, 3, 8, 9)



Output:

10 is an even number
5 is an odd number
3 is an odd number
8 is an even number
9 is an odd number

Implementation

Approach 1: Using for loop with if-else statements

Below is the code of the above approach:




#!/usr/bin/perl
# your code here
  
@arr = (10,15,21,69,42,5,3,11,28,63,7,11);
$size = @arr;
  
# For loop
  
for ($i = 0; $i < $size; $i++){
    if (@arr[$i] % 2 == 0){
        print("@arr[$i] is an even number\n");
    }
    else{
        print("@arr[$i] is an odd number\n");
    }
}

Output:

 

Approach 2: Use foreach loop with if-else Statement

Below is the Perl program to implement the above approach:




#!/usr/bin/perl
  
@arr = (10,15,21,69,42,5,3,11,28,63,7,11);
  
# For-Each loop
  
foreach $num (@arr){
    if ($num % 2 == 0){
        print("$num is an Even Number\n");
    }
    else{
        print("$num is an Odd Number\n");
    }
}

Output:

 

Approach 3: Using while Loop with if-else Statements

Below is the Perl program to implement the above approach:




#!/usr/bin/perl
# your code here
  
@arr = (10,15,21,69,42,5,3,11,28,63,7,11);
$size = @arr;
  
$count = 0;
  
while ($count < $size){
    if (@arr[$count] % 2 == 0){
        print("@arr[$count] is Even Number\n");
    }
    else{
        print("@arr[$count] is Odd Number\n");
    }
    $count++;
}

Output: 

 


Article Tags :