8
I am beginning to program in C and I realized this problem whose statement is the following:
Write an exercise that asks the user for a one-month number and prints the name of the month on the screen. For example, the user enters 1 and the program writes "January". If you enter a number that does not match any month, you should write an appropriate error message on the screen.
For now, I only know the basics (if
, else
...), so I did so:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int mes;
printf("Numero do mes: \n");
scanf("%d",&mes);
if (mes == 1)
printf("Janeiro\n");
else if (mes == 2)
printf("Fevereiro\n");
else if (mes == 3)
printf("Marco\n");
else if (mes == 4)
printf("Abril\n");
else if (mes == 5)
printf("Maio\n");
else if (mes == 6)
printf("Junho\n");
else if (mes == 7)
printf("Julho\n");
else if (mes == 8)
printf("Agosto\n");
else if (mes == 9)
printf("Setembro\n");
else if (mes == 10)
printf("Outubro\n");
else if (mes == 11)
printf("Novembro\n");
else if (mes == 12)
printf("Dezembro\n");
else if ((mes<1) || (mes>12))
printf("Erro\n");
return 0;
}
How can I solve this same problem with a more simplified code?
Search by switch/case command.
– anonimo
Note that in your program you test all valid month numbers (1 to 12) so there is no need for the last if.
– anonimo
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site
– Maniero