Home > OS >  How to convert integer input to display a character
How to convert integer input to display a character

Time:03-11

I want to create a c code that converts an integer input to a character.

For example:

When the user inputs 1 it assigns and outputs the letter as a when user inputs 2 it assigns and outputs the letter as b

it will then print out the letter ""printf("%c", letter);""

CodePudding user response:

Here is the code. The logic is how C treats chars.

int main()
{
    int num=0;
    printf("Enter a number between 1 and 26 \n");
    scanf("%d",&num);

    printf("%c",'a'-1 num);




    return 0;
}

CodePudding user response:

On most current computers letters A to Z (and lowercase equivalents) are consecutive and sequential. When you know the value of any letter you can add 1 for the next, 2 for skipping one, ...

The value of A is 'A' (or, in all the computers you have access to, 65)... so to print an lowercase L do

putchar('a'   11);

More examples

putchar('a' - 1); // prints something I don't know by heart what :)
putchar('a'   0); // prints a
putchar('a'   25); // prints z
putchar('a'   26); // prints something I don't know by heart what :)

putchar('A' - 1); // prints something I don't know by heart what :)
putchar('A'   0); // prints A
putchar('A'   25); // prints Z
putchar('A'   26); // prints something I don't know by heart what :)

putchar('g' - 2); // prints e
putchar('g'   2); // prints i
  •  Tags:  
  • c
  • Related