Correlating letters with unknown numeric values in table - C++

I have a simple task to write a print function where you print a multiplication table based on an unknown user input number n. The table should be nxn.

The user inputs just one number, n.

The columns should be labeled ABCDE etc. The rows are the number n.

  1. I know how to write this if "n" are two different variables, but for an nXn where n is the same number, I'm not sure how to write the for loop.

  2. Bigger question: how do I write a loop that corresponds an unknown number user input with the letters of the alphabet?

1 answer

  • answered 2018-12-05 21:12 Thomas Matthews

    You can convert numbers to letters and letters to numbers by using an array (a.k.a. lookup table):

    static const char Letters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char number_to_letter = Letters[number];
    //..
    for (size_t i = 0; i < sizeof(Letters) - 1U; ++i)
    {
      if (Letters[i] == character_to_number)
      {
         number = i;
         break;
      }
    }
    

    The above code assumes your numeric range is 0 to 25, inclusive.
    You can adjust the code if your range is otherwise.