Question:
Perl-Even/Odd-I am trying to get a user to enter 10 integers and multiply the odd elements and add the even.?
lamar211us
2007-02-20 07:04:28 UTC
I am totally lost. Any advise would be appreciated.

#!/usr/local/bin/perl
@NumberArray = (0,0,0,0,0,0,0,0,0,0);
@EvenArray = (0,0,0,0,0,0,0,0,0,0);
@OddArray = (0,0,0,0,0,0,0,0,0,0);
$count1 = 1;
$count2 = 0;
$count3 = 0;
$EvenTotal = 0;
$OddTotal = 0;
print "Enter your first number: ";
chomp ($NumberArray[0] = );
while ($count1 != 9)
{
print "Enter your next number: ";
chomp ($NumberArray[$count1] = );
$count1 ++;
}
print "Enter your last number: ";
chomp ($NumberArray[$count1] = );
while ($NumberArray[$count2] % 2 eq 0)
{
$EvenArray[$count2] = $NumberArray[$count2];
$EvenTotal = $EvenTotal + $EvenArray[$count2];
$count2 ++;
}
while ($NumberArray[$count3] % 2 eq 1)
{
$OddArray[$count3] = $NumberArray[$count3];
$OddTotal = $OddTotal * $OddArray[$count3];
$count3 ++;
}
#print "The numbers you entered were @NumberArray.\n";#
#print "@EvenArray\n";#
print "$EvenTotal\n";
print "$OddTotal\n";
Three answers:
martinthurn
2007-02-20 20:14:57 UTC
Don't use while loops. Use a foreach loop, because you need to look at each number exactly once.



foreach my $i (@NumberArray)

{

if $i is even, do the even stuff

elsif $i is odd, do the odd stuff

}
Eddie V
2007-02-20 07:13:27 UTC
to check for even/odd use a simple if and 3 counters. if the number is even, store it in the even-array and increment even-counter, else in the odd-array and increment odd-counter. increment overall counter after the if.



your % on the while instruction is not a good practice to use with arrays. for example, if the first number is odd, youll never get inside the loop because it says to enter while (number % 2 eq 0), so if number is 1 (1 % 2 eq 1) and you never got inside the while loop.
larkale07
2007-02-20 07:10:36 UTC
It would be helpful to mention what programming language you are using.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...