Hi, I need this program written in Java for my intro CS class. Thank you in advance. (also here is the description given in class for the code)
Write a program that displays all the leap years, ten per line, from 101 to 2100, separated by exactly one space. Also display the number of leap years in this period.
- You should use the method isLeap which returns "true" if the year is a leap year, otherwise it should return false.
- In your main(), run a loop with year with iterating from 101-2100 and just invoke the isLeap() method that you wrote.
- For the printing, use System.out.print(year+" "); to print each year separated by a white space.
- Use a counter to keep track of the number of leap years you found inside, if this number is divisible by 10, then print a blank line. This will ensure 20 numbers are printed on each line.
-Finally after the loop ends, print the counter.
The explanation is done in the code itself. if any queries write a comment. If it is helpful or understood upvote Thank you.
SOLUTION:
public class HelloWorld{
static boolean isLeap(int year){
// a year which is divisible by 400 is leap year so return
true
if(year % 400 == 0)
{
return true;
}
//a year which is divisible 100 but not with 400 is not leap year
since it is not entered in the previous condition that divisible by
400 and it divisible 100 so it is not a leap year
else if (year % 100 == 0)
{
return false;
}
//normal one a year divisible by 4 is leap year
else if(year % 4 == 0)
{
return true;
}
//if not divisible by 4 and 400 is not a leap year
else
{
return false;
}
}
public static void main(String []args){
//declare counter to store the leap years details
int counter=0;
//iterate through the years
for(int i=101;i<=2100;i++){
//check fot leap year if it is true
if(isLeap(i)){
//increase counter and print number and if mod 10 is 0 print a new
line
counter++;
System.out.print(i+" ");
//for new line after 10 numbers
if(counter%10==0){
System.out.println("");
}
}
}
//print the total count
System.out.println("\nTotal leap years are "+counter);
}
}
CODE AND OUTPUT:
Get Answers For Free
Most questions answered within 1 hours.