WeBWorK Problems

If / else loops and wanting to skip numbers

If / else loops and wanting to skip numbers

by Teresa Adams -
Number of replies: 5
If I wanted to have a "if/else" loop and I wanted it to count the numbers as "if i = 0, 3, 6, 9, .., 21" how would I code it? Would it be:

if ($i==(0, 21, 3))


Also, is there a place where I can find all the commands and coding help needed? Any help is much appreciated. Thanks,
Teresa
In reply to Teresa Adams

Re: If / else loops and wanting to skip numbers

by Alex Jordan -
Hi Teresa,

You can get coding help at this level by Googling how to do things in Perl. (As opposed to issues with MathObjects, Contexts, and other things that are specific to WeBWorK's PG modules.)

It sounds like you might want to use a loop through the full array 0 through 21, and that you might be interested in the modulus operator, which is the percent character. If I understand right, you could do:

for $i (0..21) {
if ($i % 3 == 0) {do this;}
else {do that;}
}

Does that help?

If you only want to take action on multiples of 3, you could generate the array (0,3,...,21) and do like this:

for $i map{3*$_} (0..7) {
do this;
}

The part that goes "map{3*$_} (0..7)" is taking the array 0 through 7, multiplying everything by 3, and leaving you with (0, 3, 6, 9, 12, 15, 18, 21). Then $i only iterates through those values.
In reply to Alex Jordan

Re: If / else loops and wanting to skip numbers

by Teresa Adams -
Thanks, that helps a lot. If I used:

for $i (0..21) {
if ($i % 3 == 0) {do this;}
elsif ($ % 3 ==1 {do that;}
else {do that;}
}

would the the "elsif" work for i=1, 4, 7, etc?

and else work for i = 2, 5, 8, 11?

Thanks,
Teresa
In reply to Teresa Adams

Re: If / else loops and wanting to skip numbers

by Alex Jordan -
Yes, that should work except for some typos. ("$" instead of "$i" and a missing close paren.)


In reply to Teresa Adams

Re: If / else loops and wanting to skip numbers

by Danny Glin -
It looks like you are trying to do things in groups of three. Rather than nesting an if/else statement inside a loop, you could set three consecutive values in each loop iteration. Consider the following:

for $i (0..7) {
do stuff to 3*$i;
do stuff to 3*$i+1;
do stuff to 3*$i+2;
}

This would be a little bit more efficient than what you have written. For small numbers of iterations, you probably won't notice a difference, but it can start to slow things down if the situation gets large.