# Code doesn't work for some inputs

I'm having some issues with caesar. Some things work, others don't. For example check50 says:

``````:) encrypts "a" as "b" using 1 as key
:( encrypts "barfoo" as "yxocll" using 23 as key
\ expected output, but not "yx��k����\n"
:) encrypts "BARFOO" as "EDUIRR" using 3 as key
:) encrypts "BaRFoo" as "FeVJss" using 4 as key
:( encrypts "barfoo" as "onesbb" using 65 as key
\ expected output, but not "������������\n"
:( encrypts "world, say hello!" as "iadxp, emk tqxxa!" using 12 as key
\ expected output, but not "��dgxp, hm�� tqxxd!\n"
``````

It seems to me like there is something wrong with my math, but I have no idea what. This is the relevant part of my code:

`````` if (isupper(txt[i]))
{
char fin = txt[i] + k;

if (fin > 90)
{
fin = txt[i] % k + 65;
}

printf("%c", fin);
}

if (islower(txt[i]))
{
char fin = txt[i] + k;

if (fin > 122)
{
fin = txt[i] % k + 97;
}

printf("%c", fin);
}
``````

``````fin = txt[i] % k + 65;
``````

In case `fin > 90`, and assuming that `txt[i]` is an uppercase `char` (has a value in [65 - 90]), the formula `txt[i] % k + 65` gets `fin` to have a value from 65 up to 65 + (k - 1). See why?

Similarly,

``````fin = txt[i] % k + 97;
``````

gets `fin` to have a value from 97 up to 97 + (k - 1)

This is definitely wrong because we don't know `k` beforehand. It can sometimes be a positive number that gets `fin` to have a value beyond the specified limits (i.e., `90` or `'Z'` in case of uppercase `char`s and `122` or `'z'` in case of lowercase `char`s).

The ciphering formula

``````c = (p + k) % 26
``````

where `c` is the ciphered `char`, `p` is the plain `char` and `k` is the key, assumes that each of your alphabetical `char`s has a value in [0 -25] when ciphering.

Meanwhile, in case of an uppercase character for example, you need to get `p` to have a value in [0 - 25], add the key to it, take the remainder of dividing the sum by `26` and get `p` back to have a value in [65 - 90] or ['A' - 'Z'] in ASCII.

Same steps are applied for lowercase `char`s except that when you get `p` back, it will need to have a value in [97 - 122] or ['a' - 'z'] of course.

• Why would I get each letter to have a value 0-25 when I want 65-90 or 97-122? Jun 27, 2014 at 18:49
• also I have no idea how to even get started doing that. I don't have to list every letter as a variable do I? Jun 27, 2014 at 18:57
• When ciphering, you need to get each letter a value in [0 - 25] because that's what the ciphering formula assumes. After ciphering, you need to get the ciphered letter back to be having a value in [65 - 90] or [97 - 122] accordingly.
– kzidane
Jun 27, 2014 at 18:58
• Well, think of it like that! `A`, `B`, `C` ... `Z` have ASCII values of `65`, `66`, `67`...`90`. Now, you've to ask yourself what should you do to their values to get them equal to `0`, `1`,`2` ... `25`?
– kzidane
Jun 27, 2014 at 19:02
• And of course same thing for the lowercase letters!
– kzidane
Jun 27, 2014 at 19:11