I’m a beginner in C and currently in college. I got a task to make a simple alphabet decoder. I need to input 10 numbers in between 1 and 26, each number representing a letter of the alphabet. So 1 is A, 2 is B,… Z is 26.
int c1, c2, c3, c4, c5, c6, c7, c8, c9, c10;
scanf("%d %d %d %d %d %d %d %d %d %d", &c1, &c2, &c3, &c4, &c5, &c6, &c7, &c8, &c9, &c10);
I wrote this for the input, and now I was thinking of making a switch statement for each number, but it seems inpractical to have 10 switch statements. Is there any way for me to somehow make a switch statement that repeats for each input number in consecutive order?
>Solution :
Assuming ASCII encoding, you can convert an integer in the range 1 to 26 to a letter from 'A' to 'Z' this way:
char a1 = 'A' + (c1 - 1);
You can then print the letter with
putchar(a1);
or store it into an array along with the other ones.
If you are required to use a switch statement, you can abuse the rule this way:
int int2char(int c) {
if (c >= 1 && c <= 26)
switch (c) { default: return 'A' + (c - 1); }
else
return '?';
}
Or this way (less likely to cause a warning):
int int2char(int c) {
switch (c >= 1 && c <= 26) {
case 1: return 'A' + (c - 1);
default: return '?';
}
}