Search code examples
algorithmcomputer-science

Print ASCII table without loop


I just had an interview and I have been asked a question: How would you print all the ASCII table characters without using a loop. The language doesn't matter.


Solution

  • The only method for doing so that comes to my mind is by using recursion instead of loops. An algorithm for doing this will be something like:

    void printASCII(int i){
        if(i == 128)
            return;
        print(i + " " + ((char)i) + "\n");
        printASCII(i + 1);
    }
    

    You should call the previous function using:

    printASCII(0);
    

    This will print the complete ASCII table, where each line contains the index followed by a space and the actual ASCII character.

    I don't think you can find any other way to do so, specially that it clearly says:

    The language doesn't matter

    This usually means that the question is about an algorithmic idea, rather than being specific for any language.