Click here to Skip to main content
15,901,853 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
#include<stdio.h>
int main(void)
{   int month;
    print("Enter month (1-12) number:");
    scanf("%d %d",&month);
    switch(month)
    {   case 1:
        printf("January"); break;
        case 2:
        print("February"); break;
        case 3:
        print("March"); break;
        case 4:
        printf("ApriI"); break;
        case 5:
        printf("Julay"); break;
        case 6:
        printf("June"); break;
        case 7:
        printf("July"); break;
        case 8:
        printf("August"); break;
        case 9:
        printf("September"); break;
        case 10:
        printf("October"); break;
        case 11:
        printf("November"); break;
        case 12:
        printf("December"); break;
        default:
        printf("Not a vaiid month number"); break;
        }
return 0;
}


This is my coding, i plan to change it from switch to array , may i know how?
Posted

1 solution

Put the months in an array:
string months[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};


And simply use that to lookup the month in text, like this:
printf(months[month-1]);


Good luck!
 
Share this answer
 
Comments
Jayfam 21-Apr-11 10:31am    
i do not understand with this printf(months[month-1]);
E.F. Nijboer 21-Apr-11 10:50am    
Because the array goes from 0 (Januari) to 11 (December) you need to subtract 1 from the month as number. So Januari is normally month 1, and in the array this is element 1-1=0, therefor months[0]. For February this is 2, and in the array this is element 2-1=1, therefor months[1]. Etc... So the month number minus one is the corresponding index in the array and can therefor be used to get the month in text from the array. It is actually quite simple. It is a direct translation between the value entered (in this case month number) and array index.
Jayfam 21-Apr-11 10:55am    
thx...understnad
[no name] 21-Apr-11 10:32am    
Nice one!
my 5++
Jayfam 21-Apr-11 10:34am    
can show me roughly the coding, because i new in array

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