Click here to Skip to main content
15,888,984 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How would I create a piece of code that asks the user to input a number representing the month (Jan=1, Feb=2 etc.) and outputs the month and the number of days in that month. and also get the amount of days in a month if it is a leap year following these steps
1. If the year is evenly divisible by 4, go to step 2. ...
2. If the year is evenly divisible by 100, go to step 3. ...
3. If the year is evenly divisible by 400, go to step 4. ...
4. The year is a leap year (it has 366 days).
5. Else, the year is not a leap year (it has 365 days).

What I have tried:

help would be greatly appreciated thanks
Posted
Updated 9-Jun-19 21:26pm

First off, you need to get the user to enter the year as well as the month!

The simple solution is to use the built in classes:
C#
DateTime startOfMonth = new DateTime(year, month, 1);
int daysInMonth = startOfMonth.AddMonths(1).AddDays(-1).Day;

But ... if you hand that in, you will probably get thrown off the course ... you could use it to check your code though!

Since this is your homework, I won't give you code you can hand in:
Read in teh month and year, and use int.TryParse[^] to convert them to integers.
Then just follow the rules: if it's not February, it's trivial: month to days is constant, so you could use a switch or an array of constant values to convert it.
If it is February, then follow the rules. To check if something is divisible, use the modulus (or remainder) operator[^] if the remainder of a /b is zero, then a is divisible by b.

Give it a try - see how far you can get!
 
Share this answer
 

Your algorithm for finding a leap year is a bit confusing. This algorithm is easier to follow:

Rule 1:

If the year is divisible by 4 AND the year is NOT divisible by 100, it is a leap year

Rule 2:

If the year is divisible by 400, it is a leap year.

The two statements in rule 1 can be joined by a logical AND. Rule 1 can be joined to rule 2 by using a logical OR statement to give you the result in one line of code. You can check the result using the DateTime.IsLeapYear method.

 
Share this answer
 
v3
C#
int month = 1; // January
int year = 2019;
int days = DateTime.DaysInMonth(year, month);
For checking if it's a leap year, you can either implement your steps with the help of the modulo operator % (if a % b gives the remainer of a divided by b, so if a is divisible by b, a % b is zero) or you can just use DaysInMonth to check if February has 29 days:
C#
int year = 2020;
bool leapYear = DateTime.DaysInMonth(year, 2) == 29;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900