Hour of Code: Code with Mary

Part 5: Choose My Clothing!

Putting it all together!

Putting It All Together

We've learned quite a bit up to this point and now it's time use all of our new skills to write a program that will detect if a number is even or odd.

We are going to test a range of numbers, so we need to loop from a starting number to a stopping number.

Try it!

First create a number variable called testNumber and set it to your starting number.

Next, set up a repeat loop using repeat until and for the condition specify the number to stop at.

Finally, don't forget to include end to mark the end of the loop. Move on to the next slide when you're done.

Implementing the Logic: Part 1

Now that we have the repeat loop set up, we need to complete the code block to repeat inside the loop.

We will use the modulus operator mod to determine if a number is even or odd. Remember that the modulus operator returns the remainder when dividing two numbers, so any even number divided by two will have a remainder of 0 and any odd number will have a remainder of 1.

Try it!

Create an if statement inside the repeat loop checking the modulus of the variable:

if testNumber mod 2 = 0

end end

(Then move to the next slide)

Implementing the Logic: Part 2

Our if statement is now set up for even numbers. If we want alternative instructions to run if the number is odd, we need some kind of else condition as well.

Since there are only two possibilities (even or odd), we can use the simple default else statement here.

Try it!

Before the end in the if statement, insert a line with else to set up the block for odd numbers.

Now, to increment our testing variable by one on each pass of the loop, insert a line testNumber = testNumber + 1 just after the end of the if block. (Then move to the next slide)

Being Creative

So now we have a logical code structure set up to execute different instructions if a number is even or if it is odd inside a repeat loop that will test a range of numbers.

All we need to do now is write some instructions inside the code blocks!

For this example, let's just use an output statement to print a message depending on whether the number is even or odd. You can also try a say statement if you want to hear it. Try something like output testNumber + " is even." in the first block and then Run it.

The next slide has the full code for this section...experiment with other ideas yourself.

Example Code

number testNumber = 0

repeat until testNumber = 10

if testNumber mod 2 = 0

output testNumber + " is even"

else

output testNumber + " is odd"

end

testNumber = testNumber + 1

end

Mary's full version of the clothing picker can be found here.

Try it Yourself