For this solution, you are required to make use of a switch statement. Write a program that reads in a month of the year as a number (eg 1 for January, 4 for April) and then displays the number of days in that month. Once you have planned the basic solution, take note that leap years has an impact. However, the only impact it has is when a user has specified the value for February – you should then ask the user for the year of interest. You do not need to write specialised functionality to determine whether a year was a leap year, as C# has a build-in method which can be used. In short summary: The DateTime.IsLeapYear() method in C# can be used to check whether the specified year is a leap year.
using System;
namespace IQCalculator
{
class Program
{
static void Main(string[] args)
{
int monthNumber = -1;
Console.WriteLine("Enter the number of the month");
monthNumber = int.Parse(Console.ReadLine());
switch (monthNumber)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
Console.WriteLine("31");
break;
case 4:
case 6:
case 9:
case 11:
Console.WriteLine("30");
break;
case 2:
int Year = -1;
Console.WriteLine("Enter the year");
Year = int.Parse(Console.ReadLine());
if (DateTime.IsLeapYear(Year) == true)
Console.WriteLine("29");
else
Console.WriteLine("28");
break;
default:
throw new IndexOutOfRangeException();
}
}
}
}
Comments
Leave a comment