Program to print the number of days in a given year
Last Updated :
15 Feb, 2024
Write a program to print the number of days in a given year.
Examples:
Input: 2023
Output: 365
Explanation: The year 2023 is not a leap year, therefore the number of days are 365.
Input: 2024
Output: 366
Explanation: The year 2024 is a leap year, therefore the number of days are 366.
Approach: To solve the problem, follow the below idea:
To determine the number of days in a given year, you need to consider whether the year is a leap year or not. A year is a leap year if the following conditions are satisfied:
- The year is multiple of 400.
- The year is a multiple of 4 and not a multiple of 100.
So, if it is a leap year the year contains 366 days and if not a leap year, then no. of days in a year are 365.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
bool isLeapYear( int year)
{
return (year % 4 == 0 && year % 100 != 0)
|| (year % 400 == 0);
}
int main()
{
int year = 2024;
if (isLeapYear(year)) {
cout << "Leap year. It has 366 days." << endl;
}
else {
cout << "Common year. It has 365 days." << endl;
}
return 0;
}
|
Java
public class LeapYearChecker {
static boolean isLeapYear( int year) {
return (year % 4 == 0 && year % 100 != 0 ) || (year % 400 == 0 );
}
public static void main(String[] args) {
int year = 2024 ;
if (isLeapYear(year)) {
System.out.println( "Leap year. It has 366 days." );
} else {
System.out.println( "Common year. It has 365 days." );
}
}
}
|
Python3
def is_leap_year(year):
return (year % 4 = = 0 and year % 100 ! = 0 ) or (year % 400 = = 0 )
if __name__ = = "__main__" :
year = 2024
if is_leap_year(year):
print (f "Leap year. It has 366 days." )
else :
print (f "Common year. It has 365 days." )
|
C#
using System;
class LeapYearCheck
{
static bool IsLeapYear( int year)
{
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
static void Main()
{
int year = 2024;
if (IsLeapYear(year))
{
Console.WriteLine( "Leap year. It has 366 days." );
}
else
{
Console.WriteLine( "Common year. It has 365 days." );
}
}
}
|
Javascript
function is_leap_year(year) {
return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}
const year = 2024;
if (is_leap_year(year)) {
console.log(`Leap year. It has 366 days.`);
} else {
console.log(`Common year. It has 365 days.`);
}
|
Output
Leap year. It has 366 days.
Time Complexity: O(1)
Auxiliary space: O(1)
Share your thoughts in the comments
Please Login to comment...