3. Write a function named caesarDecipher that accepts a key value (the Caesar sh
ID: 3549104 • Letter: 3
Question
3. Write a function named caesarDecipher that accepts a key value (the Caesar shift value) as its first command-line parameter, and a string (the ciphertext) for its second parameter. Your caesarDecipher function should look like this:
caesarDecipher (shift, ciphertext):
''Returns plaintext obtained by transforming every letter in the ciphertext by a Caesar cipher by
the specified shift. Non-letter characters should remain unchanged in the plaintext.''
[Your code goes here]
return [something]
Testing
To see if your code works properly, you should first try to encrypt and then decrypt a given message, and make sure it does it right.
Here are a few things for you to try to decrypt. Note that non-letters (spaces and the single quote) are copied as-is to the ciphertext.
"gduwk ydghu lv oxnh vnbzdonhu'v idwkhu" (key is 3)
"v fnirq n ybg ba zl nhgb vafhenapr ol fjvgpuvat gb trvxb" (key is 13)
Explanation / Answer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace caesar
{
class Program
{
// the function is valid only for lowercase characters
public string caesarDecipher(int shift, string cipherText)
{
string text1 = "";
int x;
for (int i = 0; i < cipherText.Length; i++)
{
if (cipherText[i] >= 97 && cipherText[i] <= 123)
{
x = (int)(cipherText[i] - shift);
if (x < 97) // accounting for when ASCII values are less than that of a
x = 123 - (97 - x);
text1 += (char)x;
}
else
text1 += cipherText[i];
}
return text1;
}
static void Main(string[] args)
{
Program p1 = new Program();
Console.WriteLine("enter text to decipher:");
string s2 = Console.ReadLine();
Console.WriteLine("enter key");
int key2 = int.Parse(Console.ReadLine());
string mods2 = p1.caesarDecipher(key2, s2);
Console.WriteLine(" " + mods2);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.