I'm doing some Chinese zodiac assignment for my programming course in C, and I'm not sure if there's a way I can write this doe in much less lines:
int main() {
int year;
printf("Enter your year of birth: \n");
scanf_s("%i", &year);
if (year % 12 == 0) {
return 0;
} else if (year % 12 == 1) {
return 1;
} else if (year % 12 == 2) {
return 2;
} else if (year % 12 == 3) {
return 3;
} else if (year % 12 == 4) {
return 4;
} else if (year % 12 == 5) {
return 5;
} else if (year % 12 == 6) {
return 6;
} else if (year % 12 == 7) {
return 7;
} else if (year % 12 == 8) {
return 8;
} else if (year % 12 == 9) {
return 9;
} else if (year % 12 == 10) {
return 10;
} else if (year % 12 == 11) {
return 11;
}
I want to know if there's any way to optimize this code.
CodePudding user response:
You could shorten the function like in the following code snippet.
#include <stdio.h>
#include <stdlib.h>
int zodiac(void)
{
int year;
printf("Enter your year of birth: \n");
scanf("%d", &year);
if ((year % 12) == 0)
{
return 12;
}
else
{
return (year % 12);
}
}
int main()
{
printf("Your zodiac year is: %d\n", zodiac());
return 0;
}
Testing that out gives the following terminal output.
@Dev:~/C_Programs/Console/Zodiac/bin/Release$ ./Zodiac
Enter your year of birth:
1955
Your zodiac year is: 11
Give that a try and see if it meets the spirit of your project.
CodePudding user response:
year % 12
reduces the year to the range [-11 ... 11]. Use that as a starting point to get the numbers [0...11].
int chinese_zodiac = year % 12;
if (chinese_zodiac < 0) {
chinese_zodiac = 12;
}
printf("Chinese zodiac index %d\n", chinese_zodiac);
printf("Chinese zodiac number %d\n", chinese_zodiac 1);
static const char *animal[12] = { "Rat", "Ox", "Tiger", /* rest for OP to add */ };
printf("Chinese zodiac animal %s\n", animal[chinese_zodiac]);
Ref: Chinese zodiac
Note: Feb 01 2022 – Jan 21 2023 is the year of the tiger (year number 3). OP's year
may need an offset.