Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I alternate between even and odd numbers?

I want the output to show which numbers are even and which are odd. Strangely, I only get 100 is odd 100 times. Does anyone know what I did wrong?

my @zahlen = (1..100);
my $zahlen = @zahlen;

foreach (@zahlen){
    if (@zahlen % 2) {
        print "$zahlen is even\n";
    } else {
        print "$zahlen is odd\n";
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are using the wrong variables in the wrong places. You set $zahlen to a constant value outside the loop (100). You can use it as the loop iterator variable instead.

Also, you should use the scalar $zahlen instead of the array @zahlen in the if statement.

use warnings;
use strict;

my @zahlen = ( 1 .. 10 );

foreach my $zahlen (@zahlen) {
    if ( $zahlen % 2 ) {
        print "$zahlen is odd\n";
    }
    else {
        print "$zahlen is even\n";
    }
}

Prints (I changed 100 to 10 to simplify the output):

1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading