I'm using a for loop in a method to carry the result to the main function. I'm trying to use the for loop to get the month of a year and pass it on to the output from the main function.
I have nested an if loop in the for loop which I feel is probably redundant as the for loop will count to the end anyway. It's probably a basic enough problem in the code but I have been staring at it for so long that I think it's burn out on my end.
The output is returning "Doesn't Exist" for all months instead of picking out the relevant month. How do I pick out the relevant month from the for loop or is that possible with the way I have coded so far?
namespace Month_Function_Call
{
class Program
{
public static String month_name(int month)
{
String result;
result = "a";
for (int i = 0; i < 12; ++i )
{
if (i == 0)
{
result = "January";
}
if (i == 1)
{
result = "February";
}
if (i == 2)
{
result = "March";
}
if (i == 3)
{
result = "April";
}
if (i == 4)
{
result = "May";
}
if (i == 5)
{
result = "June";
}
if (i == 6)
{
result = "July";
}
if (i == 7)
{
result = "August";
}
if (i == 8)
{
result = "September";
}
if (i == 9)
{
result = "October";
}
if (i == 10)
{
result = "November";
}
if (i == 11)
{
result = "December";
}
else
{
result = "N/A";
}
}
return result;
}
static void Main(string[] args)
{
Console.WriteLine("Month 1: " + month_name(1));
Console.WriteLine("Month 2: " + month_name(2));
Console.WriteLine("Month 3: " + month_name(3));
Console.WriteLine("Month 4: " + month_name(4));
Console.WriteLine("Month 5: " + month_name(5));
Console.WriteLine("Month 6: " + month_name(6));
Console.WriteLine("Month 7: " + month_name(7));
Console.WriteLine("Month 8: " + month_name(8));
Console.WriteLine("Month 9: " + month_name(9));
Console.WriteLine("Month 10: " + month_name(10));
Console.WriteLine("Month 11: " + month_name(11));
Console.WriteLine("Month 12: " + month_name(12));
Console.WriteLine("Month 43: " + month_name(43));
Console.ReadKey();
}
}
monthin theifstatements?Mainto pass month1to12. Also look intoDictionary<TKey,TValue>so that you can get ride of theifstatement in your method. Plus there are already methods available to get Month name based on number. One last thing is you needif ... else ... ifto sort out invalid choice, you may useswitchhere as well.intrepresenting the month, but you never reference that object. You method should use the information from its parameters in calculating a result.