Open In App

Program to count number of days between two given months

Last Updated : 19 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Write a program to count the number of days between two given months (including start as well as end month). Assume the number of days in February as 28.

Examples:

Input: startMonth = “january”, endMonth =”january”
Output: 31
Explanation: January has 31 days.

Input: startMonth = “january”, endMonth = “july”
Output: 212
Explanation: 31 + 28 + 31 + 30 + 31 + 30 + 31 = 212 days are present between January and July.

Approach: To solve the problem, follow the below idea:

Traverse over all the month starting from the first month till we reach the end month. While traversing over the array, sum the number of days and print the final sum.

Below is the implementation of the above approach:

C++
#include <iostream>
using namespace std;

int getMonthNumber(string month) {
    if(month == "january")
    return 1;
    else if(month == "february")
    return 2;
else if(month == "march")
    return 3;
else if(month == "april")
    return 4;
else if(month == "may")
    return 5;
else if(month == "june")
    return 6;
else if(month == "july")
    return 7;
else if(month == "august")
    return 8;
else if(month == "september")
    return 9;
else if(month == "october")
    return 10;
else if(month == "november")
    return 11;
else if(month == "december")
        return 12;
return -1;
}

void calculateNumberOfDays(string start_month, string end_month) {
    int start_month_num = getMonthNumber(start_month);
    int end_month_num = getMonthNumber(end_month);
    int ans = 0;
    if(start_month_num == -1 || end_month_num == -1 || start_month_num > end_month_num) {
        cout << "Invalid Input" << endl;
        return;
    }
    
    int arr[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    for(int i = start_month_num; i <= end_month_num; i++) {
        ans = ans + arr[i];
    }
    cout << ans << endl;
}

int main() {
    
    string start_month = "january";
    string end_month = "july";
    calculateNumberOfDays(start_month, end_month);
    
    return 0;
}
Java
public class Main {

    // Function to get the numerical representation of a
    // month
    public static int getMonthNumber(String month)
    {
        if (month.equals("january"))
            return 1;
        else if (month.equals("february"))
            return 2;
        else if (month.equals("march"))
            return 3;
        else if (month.equals("april"))
            return 4;
        else if (month.equals("may"))
            return 5;
        else if (month.equals("june"))
            return 6;
        else if (month.equals("july"))
            return 7;
        else if (month.equals("august"))
            return 8;
        else if (month.equals("september"))
            return 9;
        else if (month.equals("october"))
            return 10;
        else if (month.equals("november"))
            return 11;
        else if (month.equals("december"))
            return 12;
        return -1;
    }

    // Function to calculate the number of days between two
    // months
    public static void
    calculateNumberOfDays(String startMonth,
                          String endMonth)
    {
        int startMonthNum = getMonthNumber(startMonth);
        int endMonthNum = getMonthNumber(endMonth);
        int ans = 0;
        if (startMonthNum == -1 || endMonthNum == -1
            || startMonthNum > endMonthNum) {
            System.out.println("Invalid Input");
            return;
        }

        int[] daysInMonth = { 0,  31, 28, 31, 30, 31, 30,
                              31, 31, 30, 31, 30, 31 };
        for (int i = startMonthNum; i <= endMonthNum; i++) {
            ans += daysInMonth[i];
        }
        System.out.println(ans);
    }

    public static void main(String[] args)
    {
        String startMonth = "january";
        String endMonth = "july";
        calculateNumberOfDays(startMonth, endMonth);
    }
}
Python
def get_month_number(month):
    # Dictionary mapping month names to corresponding numbers
    months = {
        "january": 1,
        "february": 2,
        "march": 3,
        "april": 4,
        "may": 5,
        "june": 6,
        "july": 7,
        "august": 8,
        "september": 9,
        "october": 10,
        "november": 11,
        "december": 12,
    }
    # Return the month number using the dictionary, default to -1 if not found
    return months.get(month.lower(), -1)

def calculate_number_of_days(start_month, end_month):
    # Get the month numbers for start and end months
    start_month_num = get_month_number(start_month)
    end_month_num = get_month_number(end_month)
    ans = 0

    # Check for invalid input conditions
    if start_month_num == -1 or end_month_num == -1 or start_month_num > end_month_num:
        print("Invalid Input")
        return

    # Number of days in each month (index 0 is not used)
    days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    
    # Calculate the total number of days between start and end months
    ans = sum(days_in_month[start_month_num : end_month_num + 1])

    # Print the result
    print(ans)

if __name__ == "__main__":
    # Example usage
    start_month = "january"
    end_month = "july"
    calculate_number_of_days(start_month, end_month)
C#
using System;

public class Solution
{
    // Function to get the numerical representation of a month
    public static int GetMonthNumber(string month)
    {
        // Convert the month string to lowercase for case-insensitive comparison
        switch (month.ToLower())
        {
            case "january":
                return 1;
            case "february":
                return 2;
            case "march":
                return 3;
            case "april":
                return 4;
            case "may":
                return 5;
            case "june":
                return 6;
            case "july":
                return 7;
            case "august":
                return 8;
            case "september":
                return 9;
            case "october":
                return 10;
            case "november":
                return 11;
            case "december":
                return 12;
            default:
                return -1; // Return -1 for invalid input
        }
    }

    // Function to calculate the number of days between two months
    public static void CalculateNumberOfDays(string startMonth, string endMonth)
    {
        // Get the numerical representation of startMonth and endMonth
        int startMonthNum = GetMonthNumber(startMonth);
        int endMonthNum = GetMonthNumber(endMonth);
        int ans = 0;

        // Check for invalid input or if startMonth is greater than endMonth
        if (startMonthNum == -1 || endMonthNum == -1 || startMonthNum > endMonthNum)
        {
            Console.WriteLine("Invalid Input");
            return;
        }

        // Array to store the number of days in each month
        int[] daysInMonth = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        
        // Iterate over the months from startMonth to endMonth and calculate total days
        for (int i = startMonthNum; i <= endMonthNum; i++)
        {
            ans += daysInMonth[i];
        }

        // Print the total number of days
        Console.WriteLine(ans);
    }

    // Main method serving as the entry point
    public static void Main(string[] args)
    {
        string startMonth = "january";
        string endMonth = "july";
        CalculateNumberOfDays(startMonth, endMonth);
    }
}
JavaScript
// Function to get the numerical representation of a month
function getMonthNumber(month) {
    switch (month.toLowerCase()) { // Convert month to lowercase for case-insensitivity
        case "january":
            return 1;
        case "february":
            return 2;
        case "march":
            return 3;
        case "april":
            return 4;
        case "may":
            return 5;
        case "june":
            return 6;
        case "july":
            return 7;
        case "august":
            return 8;
        case "september":
            return 9;
        case "october":
            return 10;
        case "november":
            return 11;
        case "december":
            return 12;
        default:
            return -1; // Invalid month
    }
}

// Function to calculate the number of days between two months
function calculateNumberOfDays(startMonth, endMonth) {
    const startMonthNum = getMonthNumber(startMonth);
    const endMonthNum = getMonthNumber(endMonth);
    let ans = 0;
    // Check for invalid input or out of order months
    if (startMonthNum === -1 || endMonthNum === -1 || startMonthNum > endMonthNum) {
        console.log("Invalid Input");
        return;
    }

    // Array representing days in each month
    const daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    // Calculate total days by summing days of months between start and end
    for (let i = startMonthNum; i <= endMonthNum; i++) {
        ans += daysInMonth[i];
    }
    console.log(ans); // Output total days
}

// Main function to test the above functions
function main() {
    const startMonth = "january";
    const endMonth = "july";
    calculateNumberOfDays(startMonth, endMonth);
}

main(); // Execute main function

Output
212

Time Complexity: O(1)
Auxiliary Space: O(1)



Similar Reads

Program to count the number of months between given two years
Given a start year and end year. Write a program to count number of months between given two years (both inclusive). Examples: Input: startYear = 1991, endYear = 2023Output: 396Explanation: The number of years between 1991 and 2023 (both inclusive) are: 33. So, total number of months = 396. Input: startYear = 2010, endYear = 2023Output: 168Explanat
4 min read
Program to count the number of days between two years
Given two years. Write a program to count the number of days between the two years. Examples: Input: startYear = 1990, endYear = 2001Output: 4383 Explanation: Years 1992, 1996 and 2000 are leap year and all 9 others are non-leap years. So, total number of days are: 366 * 3 + 365 * 9 = 4383 Input: startYear = 1890, endYear = 1998Output: 39811 Approa
4 min read
Program to print the number of days in a given year
Write a program to print the number of days in a given year. Examples: Input: 2023Output: 365Explanation: The year 2023 is not a leap year, therefore the number of days are 365. Input: 2024Output: 366Explanation: 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 t
4 min read
Program to find the number of days in a given month
Write a program to find the number of days in a given month. We are given name of a month in lowercase letters, so print the number of days in the month. Note: For February, consider the number of days as 28. Examples: Input: month = "january"Output: 31Explanation: January has 31 days. Input: month = "february"Output: 28Explanation: February has 28
3 min read
Program to convert days to weeks
Write a program to convert a given number of days to weeks. Examples: Input: 14 daysOutput: 2 weeks Input: 30 daysOutput: 4 weeks and 2 days Approach: To solve the problem, follow the below idea: Divide the given number of days by 7 to get the number of weeks. The remainder will be the remaining days. Step-by-step algorithm: Read the number of days
2 min read
Program to convert weeks to days
Given no of weeks. Write a program to convert weeks to days. Examples: Input: weeks = 4Output: 28 days Input: weeks = 2Output: 14 days Approach: To solve the problem, follow the below idea: Since we know a week has 7 days. So, to find no of days in a week, we multiply weeks by 7. 1 week = 7 daysn weeks = n*7 days Below is the implementation of the
3 min read
Program to generate a random two-digit number
Write a program to generate a random two-digit number. Example 1: 73Example 2: 26 Approach: To solve the problem, follow the below idea: We can generate a random two-digit number by generating a random integer first and then modulo it by 90. Now, after modulo 90 the remainder can be in the range 0 to 89, so in order to have the remainder as a two-d
2 min read
Program to count the number of consonants in a word
Write a program to count the number of consonants in a given word. Consonants are the letters of the English alphabet excluding vowels ('a', 'e', 'i', 'o', 'u'). Examples: Input: "programming"Output: 8 Explanation: The eight consonants are: 'p', 'r', 'g', 'r', 'm', 'm', 'n', 'g') Input: "hello"Output: 3 Explanation: There are three consonants: 'h',
5 min read
Program to count the number of characters in a word
Write a program to count the number of characters in a word. Examples: Input: Word: "programming"Output: 11 Input: Word: "hello"Output: 5 Approach: To solve the problem, follow the below idea: To count the number of characters in a word, maintain a variable to count all the characters. Iterate through each character in the word and increment the co
2 min read
Program to count the number of vowels in a word
Write a program to count the number of vowels in a given word. Vowels include 'a', 'e', 'i', 'o', and 'u' (both uppercase and lowercase). The program should output the count of vowels in the word. Examples: Input: "programming"Output: 3Explanation: The word "programming" has three vowels ('o', 'a', 'i'). Input: "HELLO"Output: 2Explanation: The word
3 min read
Article Tags :