I'm trying to find the leap years and non leap years within a number range. The leap year and non leap years need to be put into separate arrays and I will be outputting them into a table later. I'm pretty new to JavaScript and I suspect that my looping may be wrong, i'm not sure.
My problem is that the non-leap year array is not getting all the numbers it needs. I enter 1900 - 2000 and the leap years seem to be alright, but the non leap year array only went up to 1930. I've been trying to fix it for a while, but I've had no luck.
Edit: The for
loops are there only for me to test the arrays.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>LeapYears</title>
<script type="text/javascript">
/* <![CDATA[ */
function calcLeapYear() {
var beginYear = document.leapYears.firstYear.value;
var endYear = document.leapYears.secondYear.value;
var leapYrs = new Array();
var nonLeapYrs = new Array();
var ctr = 0
var ctr2 = 0
while (beginYear < endYear){
if (((beginYear % 4 == 0) && (beginYear % 100 != 0)) || (beginYear % 400 == 0)) { /* Determines if year is a leap year or not */
leapYrs[ctr] = beginYear;
++ctr;
}
else {
nonLeapYrs[ctr2] = beginYear;
++ctr2;
}
++beginYear;
}
if (leapYrs == 0){
window.alert("There were no leap years within the range.");
}
for (i=0;i<leapYrs.length;i++){ //Testing Calculation
document.write(leapYrs[i] + "<br/>");
}
document.write("<br/>")
for (i=0;i<leapYrs.length;i++){
document.write(nonLeapYrs[i] + "<br/>");
}
}
/* ]]> */
</script>
</head>
<body>
<form name="leapYears">
Beginning Year: <input type="text" name="firstYear" /> End Year: <input type="text" name="secondYear" />
<input type="button" value="Find Leap Years" onclick="calcLeapYear()" />
</form>
</body>
</html>
Your loop when you document.write
the contents of nonLeapYrs
is looping over only the length of leapYrs
so it will only print part of the array.