LearnFrenzy
Sign in Take a free test

C Const · const Programs · Question 6

Unit conversion using a const table of factors in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Convert one value with several conversion factors stored in a read-only table.

Solution
main.c
#include <stdio.h>

static const struct {
    const char *from, *to;
    double factor;
} conv[] = {
    {"km", "miles", 0.621371},
    {"kg", "pounds", 2.20462},
    {"litres", "gallons (US)", 0.264172},
};

int main(void) {
    const double value = 10.0;
    for (size_t i = 0; i < sizeof conv / sizeof conv[0]; i++)
        printf("%.1f %s = %.2f %s\n", value, conv[i].from, value * conv[i].factor, conv[i].to);
    return 0;
}

Output Verified by compiling and running

10.0 km = 6.21 miles
10.0 kg = 22.05 pounds
10.0 litres = 2.64 gallons (US)

Data-driven code: adding a conversion means adding one table row. The trailing comma after the last row is allowed in C initializers and makes such tables easy to extend.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links