The biggest problem here is that you are treating the representation of letters as numbers from 0 to 25 when they are represented as ASCII values. You're on the right track, but there's an important step missing. Try working out an example of your code on paper. This is a very useful technique.
For instance, use a key of 2
and try to encode a
. Now, using the formula (s[i] + k) % 26 )
, plug in the numbers. The ASCII value for a
is 97, so the formula becomes
(97 + 2) % 26 = 194 % 26 = 14
If you look at an ASCII table, you'll see that ASCII 14 is definitely not a letter. So you see, there's a serious problem with this. Your technique would work if the letters were represented by numbers from 0 to 25 instead of ASCII values.
My suggestion is to go back and review all of the class material on Caesar, along with the section video and the assignment. There are details on how to deal with ASCII values that will help you out. While I could give you a detailed answer on what to do, you'll learn much more if you work through the issues.
If this answers your question, please accept the answer so that the question is removed from the unanswered question pool. Let's keep up on forum maintenance. ;-)