Java Program to Check Leap Year Using Nested If
In this article we will be discussing a very interesting question based on nested conditional statements. In this question we have to write a java program to check for the leap year using nested if.
Question - Write a Java Program to Check Leap Year Using Nested If
Logic and Source Code
Question - Write a Java Program to Check Leap Year Using Nested If
Java Program to Check Leap Year Using Nested If - In this program we have to check for the Leap year.
So, first thing you should know is that what is the condition for leap year. Many of you just know that a leap year is that year which is divisible by 4. But this is not the complete definition of the leap year.
A leap year is that which is divisible by 4 except the end-of century years, which must be divisible by 400. This is why 1900 is not a leap year but 2000 is a leap year.
Now, let's start with the code. First we will take input the year number from the user.
import java.util.Scanner;
public class ques3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int year = sc.nextInt();
}
}
Now, the first basic condition for a leap is that it must by divisible by 4 whether it is a century year or not. So, we will first check for divisibility for 4.
if (year%4 == 0){
}
After this we will be checking whether the year is a end-century year or not. If yes, then will check for it's divisibility by 400 and if it is divisible then we can say that this year is a leap year and if it is not then it is not a leap year. Another case may be that it is not a end-century year, in that case as it is divisible by 4 we can surely say that it is a leap year.
And if it is not divisible by 4, then it is confirmed that it is not a leap year. I hope this is clear to you. Now, let's implement this in code.
if (year%4 == 0){
if (year%100 ==0){
if(year%400 ==0){
System.out.println("It's a leap year");
}
else{
System.out.println("It's not a leap year");
}
}
else{
System.out.println("It's a leap year");
}
}
else{
System.out.println("It's not a leap year");
}
Here's the complete source code for the program.
import java.util.Scanner;
public class ques3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int year = sc.nextInt();
if (year%4 == 0){
if (year%100 ==0){
if(year%400 ==0){
System.out.println("It's a leap year");
}
else{
System.out.println("It's not a leap year");
}
}
else{
System.out.println("It's a leap year");
}
}
else{
System.out.println("It's not a leap year");
}
}
}
Post a Comment