Getting the Total Number of Days in a Month Using If-else and Switch Statements in C#
Last Updated :
28 May, 2020
Given a number N, the task is to write a C# program to print the number of days in the Month N.
Examples:
Input: N = 12
Output: 31
Input: N = 2
Output: 28/29
This task can be done using the following approaches:
1. Using if else statement : Appropriate month number is checked and then number of days in a month is print using else if statement. Number of days are follows :
Month = [1, 3, 5, 7, 8, 10, 12] , Number of days = 31
Month = [2] , Number of days = 28/29
Month = [4, 6, 9, 11] , Number of days = 30
Below is the implementation of the above approach:
Output:
C#
using System;
public class GFG{
static void PrintNumberofDays( int N)
{
if (N == 1 || N == 3 || N == 5 || N == 7
|| N == 8 || N == 10 || N == 12) {
Console.Write( "31" );
}
else if (N == 4 || N == 6 || N == 9 ||
N == 11) {
Console.Write( "30" );
}
else if (N == 2) {
Console.Write( "28/29" );
}
}
static public void Main ()
{
int N = 5;
PrintNumberofDays(N);
}
}
|
Output:
31
2. Using Switch Condition : Same as Else if , here month number is checked and it is redirected to cases,and then number of days in a month is print. Below is the implementation of the above approach:
C#
using System;
public class GFG{
static void PrintNumberofDays( int N)
{
switch (N )
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
Console.Write( "31" );
break ;
case 4:
case 6:
case 9:
case 11:
Console.Write( "30" );
break ;
case 2:
Console.Write( "28/29" );
break ;
}
}
static public void Main ()
{
int N = 5;
PrintNumberofDays(N);
}
}
|
Output:
31
Share your thoughts in the comments
Please Login to comment...