For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:
Normally a year has 365 days in the Georgian calendar. But for a leap year it has 366 days instead of 365 days, by adding February to 29 days rather than the common 28. The leap year of 366 days has 52 weeks and 2 days.
To check whether the given year is a leap year or not, just divide the year by four and check the reminder. If the reminder is Zero then it is a leap year. For example, let us check the year ‘2020’ which is divisible by four, so it is a leap year.
Here we are showing how to check leap year in the Go language. We wil make use of a variable to hold the year which has to be check. fmt.scanln()
function is used to read the year to check and fmt.println()
function is used to print the string on the output screen. Here the conditional statement function if ...else
is used to perform the checking.
syntax for if....else
if condition {
//do some instructions
}else {
//do some instructions
The check is done as year % 4==0 && year % 100 != 0 || year % 400 == 0 in a if
condition. If the condition is true it is a leap year otherwise not a leap year. >Here we are using the arithmetic operator modulus %
is used to find the reminder
STEP 1: Import the package fmt
STEP 2: Start function main()
STEP 3: Declare the variable year
STEP 4: Read the year year using fmt.Scanln()
STEP 5: Use if-else
for the check
STEP 6: The condition for the check is year % 4==0 && year % 100 != 0 || year % 400 == 0
STEP 7: If the above condition is true it is a leap year otherwise not
package main
import "fmt"
func main() {
var year int
fmt.Print("Enter the year to be checked:")
fmt.Scanf("%d", & year)
if year % 4==0 && year % 100 != 0 || year % 400 == 0 {
fmt.Println("The year is a leap year!")
}else{
fmt.Println("The year isn't a leap year!")
}
}
Enter the year for Leap year check = 2020 2020 is a Leap year Enter the year for Leap year check = 1990 1990 is Not a Leap year