FRQ Answers: CSA 2019 AP Exam
Answers to the 2019 AP Exam FRQ questions
Write the static method numberOfLeapYears, which returns the number of leap years between year1 and year2, inclusive
Write the static method dayOfWeek, which returns the integer value representing the day of the week for the given date
All helper methods are included below for running.
public class years {
private static boolean isLeapYear(int year){
if(year % 4 == 0){ //conditional to check if year is divisible by 4. All years divisible by 4 are leap years
if(year % 100 == 0){ //conditional to check if year is divisible by 100. All years divisible by 100 are leap years
if(year % 400 == 0){ //conditional to check if year is divisible by 400. All years divisible by 400 are leap years
return true;
}
else{
return false;
}
}
else{
return true;
}
}
else{ //if none of these conditions are true, the year is not a leap year.
return false;
}
}
/** Returns the number of leap years between year1 and year2, inclusive.
* Precondition: 0 <= year1 <= year2
*/
private static int numberOfLeapYears(int year1, int year2){
int count = 0; //the count that will be returned
for(int i = year1; i <= year2; i++){ //loops through the years provided
if(isLeapYear(i) == true){
count++; //if the year is a leap year, add 1 to the count
}
}
return count; //return the count
}
//Finds the day of the week for first day of the year
private static int firstDayOfYear(int year){
int first1950 = 0; //day of the week in 1950
int day = first1950;
//find the difference between the year and 2000
int difference = year - 1950;
//for every integer increase in the difference, add 1 to the day.
for(int i = 0; i < difference; i++){
day++;
if(isLeapYear(1950 + i) == true){
day++;
}
}
if(day > 6){
day = day % 7;
}
return day;
}
private static int dayOfYear(int month, int day, int year){
int dayOfYear = 0;
for(int i = 1; i < month; i++){
if(i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12){ //adding 31 if month has 31 days
dayOfYear += 31;
}
else if(i == 4 || i == 6 || i == 9 || i == 11){ //adding 30 if month has 30 days
dayOfYear += 30;
}
else if(i == 2){ //checking if the year is a leap year during the feburary iteration
if(isLeapYear(year) == true){
dayOfYear += 29;
}
else{
dayOfYear += 28;
}
}
}
dayOfYear += day;
return dayOfYear;
}
private static int dayOfWeek(int month, int day, int year){
int dayOfWeek = 0;
int firstDay = firstDayOfYear(year);
int dayOfYear = dayOfYear(month, day, year) - 1;
dayOfWeek = (firstDay + dayOfYear) % 7;
return dayOfWeek;
}
}