![]() |
CPSC 110-08: Computing on Mobile Phones
|
2012 is a Leap Year. But what exactly is a leap year and what years are leap years?
This activity is a follow-up to the leap year homework assignment. The following rules defines which years are leap years:
Leap Year Definition. A year is a leap year if it is evenly divisible by 4 but not evenly divisible by 100 unless it is also evenly divisible by 400. So 1996 was a leap year. But 1900 was not a leap year because, although it is divisible by 4, it is also divisible by 100 and not by 400. 2000 is a leap year because it is divisible by 400.
Let's build an app that tells whether any given year is a leap year
or not. The user interface (UI) for this app will be as follows
(click to enlarge):
The app contains a Label with the text "Leap Year?", a TextBox where the user will enter a year, a Button that the user will click to test whether the year is a leap year, and a Notifier that will display the answer.
For homework we constructed the following blocks (click to enlarge):
The isLeapYear function was only partially completed in the homework assignment, where we had the following challenges:
A number a is divisible by b if the result of dividing a by b leaves a remainder of 0. For example, 10 is divisible by 2 because 10/2 gives a quotient of 5 and a remainder of 0. But 10 is not divisible by 3, because 10/3 gives a quotient of 3 and a remainder of 1. We can express this in pseudocode and App Inventor blocks as follows:
| Pseudocode | App Inventor Block |
|---|---|
| remainder (a, b) = 0 |
|
Thus, we see that saying a is divisible by b is the same as saying the remainder of dividing a by b is 0.
Because our leap year definition uses the concept of is divisible with several different values for b, it makes sense to define a function that we can call (just like a built-in function) whenever we want to know whether one number (the year) is divisble by another (4 or 100 or 400).
The arguments, a and b, serve as place holders into which we can place any integer values we like and the function will return either true or false:
To finish our leap year app we need to complete the definition of the isLeapYear function. What's needed is a nested if/else block that expresses the leap year definition:
Notice that three 3 individual if/else blocks nested within each other. These express the 3 divisibility tests that are needed to define a leap year.
We will be using seeing functions again in subsequent examples. But hopefully this lesson helps you see that functions can: