Question 4
Back to Exercise
Look up a product category's GST rate in a read-only table and compute the final price in paise.
Solution
#include <stdio.h>
#include <string.h>
static const struct {
const char *category;
int rate_percent;
} gst[] = {{"essentials", 5}, {"standard", 18}, {"luxury", 28}};
long price_with_gst(const char *category, long paise) {
for (size_t i = 0; i < sizeof gst / sizeof gst[0]; i++)
if (strcmp(gst[i].category, category) == 0)
return paise + (paise * gst[i].rate_percent + 50) / 100; /* rounded */
return -1; /* unknown */
}
int main(void) {
const char *cats[] = {"essentials", "standard", "luxury", "toys"};
for (int i = 0; i < 4; i++) {
long p = price_with_gst(cats[i], 100000); /* Rs. 1000.00 */
if (p < 0)
printf("%s: unknown category\n", cats[i]);
else
printf("%s: Rs. %ld.%02ld\n", cats[i], p / 100, p % 100);
}
return 0;
}
essentials: Rs. 1050.00 standard: Rs. 1180.00 luxury: Rs. 1280.00 toys: unknown category
Rates live in one read-only table, so changing a rate never touches the code. Integer paise and a rounded percentage keep the money exact.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!