From Textbook Building Java Programs 3rd addition: Chapter 4, prpblem 4 Write a
ID: 3564899 • Letter: F
Question
From Textbook Building Java Programs 3rd addition: Chapter 4, prpblem 4
Write a method called daysInMonth that takes a month (an integer between 1 and 12) as a parameter and returns the number of days in that month in this year. For example, the call daysInMonth (9) would return 30 because September has 30 days. Assume that the code is not being run during a leap year (that February always has 28 days). The following table lists the number of days in each month:
Month
1 Jan
2 Feb
3 Mar
4 Apr
5 May
6 Jun
7 Jul
8 Aug
9 Sep
10 Oct
11 Nov
12 Dec
Days
31
28
31
30
31
30
31
31
30
31
30
31
Month
1 Jan
2 Feb
3 Mar
4 Apr
5 May
6 Jun
7 Jul
8 Aug
9 Sep
10 Oct
11 Nov
12 Dec
Days
31
28
31
30
31
30
31
31
30
31
30
31
Explanation / Answer
<?php
/*
* days_in_month($month, $year)
* Returns the number of days in a given month and year, taking into account leap years.
*
* $month: numeric month (integers 1-12)
* $year: numeric year (any integer)
*
* Prec: $month is an integer between 1 and 12, inclusive, and $year is an integer.
* Post: none
*/
// corrected by ben at sparkyb dot net
function days_in_month($month, $year)
{
// calculate number of days in a month
return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year % 400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}
?>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.