Caesars Cipher Algorithm, what is wrong with my code?


I hope some can help me understand what is going on with my code.

I ma trying to solve the Caesar’s Cipher algorithm, and code seems to work for individual letters and also for couple of “opposite” letters.

But when testing it for something else the results are just weird, returning red and / or wrong letters.

Many thanks for any help out there.

The first issue I see is the for loop structure, I think what you are trying to achieve is a “while” loop using a “for” loop. I’m not saying use a while loop but just look at the syntax and structure first and move forward from there.

for (var i=0;i<str.length;i++) {}

this should be your for-loop to help you get on track

His way may look odd, but is equivalent. Nothing will change in the operation.

Try to step through your algorithm with a string that is failing. You could use a debugger, but it’s easier to just console.log what you got as input and what you replaced it with (at i, str, newstr). In each loop iteration.

1 Like

You are doing so many un necessary conditions.
Here’s a few tips to solve the problem.

  1. You need to loop through all the letters inside the string.
    so it’s alright to use for(i=0;i<str.length;i++)
  2. You only need to change the letters between A-Z which are from 65-90. Make a single if statement equivalent to that.
  3. Inside the if statement. Add a certain value to the number equivalent of the letter.
    4.if it becomes >90 add the excess to 64

Many thanks for all replies. I have tried different solutions and got one working.

Will do some testing as suggested by lynxlynxlynx and see if I can find out what’s wrong with the code I posted.