Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Single switch statement for multiple variables

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 '?';
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading