-2

I'm writing a program that when you subtract 3 from char 'a' you get the answer of char 'x'

What's the most practical way of doing this?

#include <stdio.h>

int main(void)
{
   char letter = 'a'
   int subtract_from_letter = 3;

   /*Not sure what to do here...

    char letter should now equal 'x'. If char letter was equal to 'd', it      
    would now equal 'a'.        

   */

   return 0; 
}

Thanks everyone.

4 Answers4

1

I'd do

  • convert from the letter to a respective number from 0..25,
  • add/subtract
  • do a modulo 26 operation
  • convert back to a letter.

So the result is

int letter_num = letter - 'a';
int result = (letter_num + 26 - subtract_from_letter) % 26; // ensures we stay positive
chat result_letter = result + 'a';

For example, with 'a' and 3, you'll get

letter_num = 0
result = 23
result_letter = 'x'

'd', however, will give you

letter_num = 3
result = (29 - 3) % 26 = 0
result_letter = 'a'
glglgl
  • 89,107
  • 13
  • 149
  • 217
0

I think , youre trying to go for a circular print for small case alphabets, right?

Try this logic:

  1. check if the letter is less than d (decimal 100) or not before subtraction.
  2. If yes, do (letter + 26 - subtract_from_letter)
  3. otherwise, do (letter - subtract_from_letter)
  4. print the result using %c.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 2
    Surely (`letter + 26 - subtract_from_letter)`? – Weather Vane May 19 '15 at 08:19
  • @WeatherVane is `(letter+122-subtract_from_letter)` – LPs May 19 '15 at 08:23
  • @LPs no! Start from `letter = 'c'`, so `letter = 99` then `99+26-3 = 122` which is `'z'`. – Weather Vane May 19 '15 at 08:25
  • @WeatherVane I misunderstood your comment, you right, but @Sourav Ghosh wrote `(letter + 'z' - subtract_from_letter)` that is `(letter+122-subtract_from_letter)` or I'm missing something? – LPs May 19 '15 at 08:27
  • @LPs I could have edited the incorrect answer but to be polite I queried it instead. – Weather Vane May 19 '15 at 08:30
  • @WeatherVane I really appriciate your patience. However, this kind of error is commonly due to silly mistakes anf you are always welcome to make the change in the answer body itself. No worries – Sourav Ghosh May 19 '15 at 08:34
0

a according to ASCII table is 97 dec , so when you write :

char letter = 'a';
int subtract_from_letter = 3;
int result = letter - subtract_from_letter; // 97 - 3 = 94 

94 in decimal, from ASCII table, is ^ in character.

x in decimal is 120, so if you want to get x from this calculation, you should do this:

char letter = 'a';
int subtract_from_letter = 3;
int result = letter - subtract_from_letter + 26; // 97 - 3 + 26 = 120

but, it's weird !

Diabolus
  • 268
  • 2
  • 15
0

The simplest (but safe) way is:

   char letter = 'a';
   int substract_from_letter = 3;

   letter = 'a' + ((letter + 'z' - 'a' + 1 - substract_from_letter - 'a') 
                   % ('z' - 'a' + 1));