#include <stdio.h>
#include <string.h>
#include <ctype.h>
/* ------------------------------------------------------------
CountryEntry
Represents a single ISO alpha‑2 → country name mapping.
------------------------------------------------------------ */
typedef struct {
const char *code;
const char *name;
} CountryEntry;
/* ------------------------------------------------------------
A sorted lookup table for fast binary search.
Add more entries as needed, but keep it sorted by code.
------------------------------------------------------------ */
static const CountryEntry COUNTRY_TABLE[] = {
{"CA", "Canada"},
{"CN", "China"},
{"DE", "Germany"},
{"FR", "France"},
{"GB", "United Kingdom"},
{"IN", "India"},
{"JP", "Japan"},
{"US", "United States"}
};
static const size_t COUNTRY_COUNT = sizeof(COUNTRY_TABLE) / sizeof(CountryEntry);
/* ------------------------------------------------------------
normalizeCode
Converts a 2‑letter code to uppercase for consistent matching.
------------------------------------------------------------ */
void normalizeCode(char *code) {
for (size_t i = 0; code[i] != '\0'; ++i) {
code[i] = (char)toupper((unsigned char)code[i]);
}
}
/* ------------------------------------------------------------
getCountryName
Performs a binary search on the sorted table.
Returns NULL if the code is not found.
------------------------------------------------------------ */
const char* getCountryName(const char *alpha2) {
char code[3];
strncpy(code, alpha2, 2);
code[2] = '\0';
normalizeCode(code);
size_t left = 0;
size_t right = COUNTRY_COUNT;
while (left < right) {
size_t mid = left + (right - left) / 2;
int cmp = strcmp(code, COUNTRY_TABLE[mid].code);
if (cmp == 0) {
return COUNTRY_TABLE[mid].name;
} else if (cmp < 0) {
right = mid;
} else {
left = mid + 1;
}
}
return NULL;
}
/* ------------------------------------------------------------
main
Demonstrates the lookup function with several sample codes.
------------------------------------------------------------ */
int main(void) {
const char *codes[] = {"US", "GB", "FR", "JP", "ZZ"};
const size_t count = sizeof(codes) / sizeof(codes[0]);
for (size_t i = 0; i < count; ++i) {
const char *name = getCountryName(codes[i]);
if (name) {
printf("%s → %s\n", codes[i], name);
} else {
printf("%s → (invalid code)\n", codes[i]);
}
}
return 0;
}
/*
run:
US → United States
GB → United Kingdom
FR → France
JP → Japan
ZZ → (invalid code)
*/